当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java反射机制实现toString()方法
发布时间:2010/11/21 22:27:25 来源:城市学习网 编辑:ziteng
  import java.lang.reflect.Field;
  import java.lang.reflect.InvocationTargetException;
  import java.lang.reflect.Method;
  public class TestReflection {
  public static void main(String[] args){
  User user = new User();
  user.setUserName("ZhangSan");
  user.setPassword("123456");
  try {
  printObject( user );
  } catch (SecurityException e) {
  e.printStackTrace();
  } catch (IllegalArgumentException e) {
  e.printStackTrace();
  } catch (NoSuchMethodException e) {
  e.printStackTrace();
  } catch (IllegalAccessException e) {
  e.printStackTrace();
  } catch (InvocationTargetException e) {
  e.printStackTrace();
  }
  }
  public static void printObject(Object obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
  Field[] fields = obj.getClass().getDeclaredFields();
  for(int i= 0; i<fields.length; i++){
  Field f = fields[i];
  String fieldName = f.getName();
  String stringLetter = fieldName.substring(0, 1).toUpperCase();
  String getName="get"+stringLetter+fieldName.substring(1);
  Class classType=obj.getClass();
  //获取相应的方法
  Method getMethod=classType.getMethod(getName, new Class[]{});
  //调用源对象的getXXX()方法
  Object value=getMethod.invoke(obj, new Object[]{});
  System.out.println(fieldName+": "+value);
  }
  }
  }
  class User{
  private String userName;
  private String password;
  public String getUserName() {
  return userName;
  }
  public void setUserName(String userName) {
  this.userName = userName;
  }
  public String getPassword() {
  return password;
  }
  public void setPassword(String password) {
  this.password = password;
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved