易采站长站为您分析Java反射通过Getter方法获取对象VO的属性值过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
有时候,需要动态获取对象的属性值。
比如,给你一个List,要你遍历这个List的对象的属性,而这个List里的对象并不固定。比如,这次User,下次可能是Company。
e.g. 这次我需要做一个Excel导出的工具类,导出的批量数据是以List类型传入的,List里的对象自然每次都不同,这取决于需要导出什么信息。
为了使用方便,将对象的属性名与属性值存于Map当中,使用时就可以直接遍历Map了。
此次的思路是通过反射和Getter方法取得值,然后记录在一个Map当中。
Kick start...
将对象的属性名与属性值存于Map当中,以key,value的形式存在,而value并不希望以单一类型(如String)存在(因为涉及多种类型),所以用一个FieldEntity的自定义类(此类包含属性名,属性值,属性值类型 等属性)
FieldEntity
package com.nicchagil.util.fields;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class FieldsCollector {
public static Map<String, FieldEntity> getFileds(Object object)
throws SecurityException, IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
Class clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
Map<String, FieldEntity> map = new HashMap<String, FieldEntity> ();
for (int i = 0; i < fields.length; i++) {
Object resultObject = invokeMethod(object, fields[i].getName(), null);
map.put(fields[i].getName(), new FieldEntity(fields[i].getName(), resultObject, fields[i].getType()));
}
return map;
}
public static Object invokeMethod(Object owner, String fieldname,
Object[] args) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class ownerClass = owner.getClass();
Method method = null;
method = ownerClass.getMethod(GetterUtil.toGetter(fieldname));
Object object = null;
object = method.invoke(owner);
return object;
}
}
主类,通过这个类的静态方法获取结果Map
FieldsCollector
package com.nicchagil.util.fields;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class FieldsCollector {
public static Map<String, FieldEntity> getFileds(Object object)
throws SecurityException, IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
Class clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
Map<String, FieldEntity> map = new HashMap<String, FieldEntity> ();
for (int i = 0; i < fields.length; i++) {
Object resultObject = invokeMethod(object, fields[i].getName(), null);
map.put(fields[i].getName(), new FieldEntity(fields[i].getName(), resultObject, fields[i].getType()));
}
return map;
}
public static Object invokeMethod(Object owner, String fieldname,
Object[] args) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class ownerClass = owner.getClass();
Method method = null;
method = ownerClass.getMethod(GetterUtil.toGetter(fieldname));
Object object = null;
object = method.invoke(owner);
return object;
}
}










