很多时候我们在项目中并不会知道传过来的一个对象的真实类型,自然也无法使用这个类型的get方法获取这个传过来的对象的属性和属性对应的值,当时我们使用反射则可以方便的获取传递过来的未知类对象的所有的属性(包含所有父类)值。
下面的第一个代码处理的是仅仅获取本类中的所有的属性和属性值的方法。
public static void testReflect(Object model) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Field[] field = model.getClass().getDeclaredFields(); //获取实体类的所有属性,返回Field数组
for(int j=0 ; j
String name = field[j].getName(); //获取属性的名字
System.out.println("attribute name:"+name);
name = name.substring(0,1).toUpperCase()+name.substring(1); //将属性的首字符大写,方便构造get,set方法
String type = field[j].getGenericType().toString(); //获取属性的类型
if(type.equals("class java.lang.String")){ //如果type是类类型,则前面包含"class ",后面跟类名
Method m = model.getClass().getMethod("get"+name);
String value = (String) m.invoke(model); //调用getter方法获取属性值
if(value != null){
System.out.println("attribute value:"+value);
}
}
if(type.equals("class java.lang.Integer")){
Method m = model.getClass().getMethod("get"+name);
Integer value = (Integer) m.invoke(model);
if(value != null){
System.out.println("attribute value:"+value);
}
}
if(type.equals("class java.lang.Short")){
Method m = model.getClass().getMethod("get