应用示例:
/** * 通过get方法取对象值 * @param FieldName * @param o * @return */ public static Object getFieldValueByObject(String FieldName,Object o){ PropertyDescriptor pd; Object resultO = null; try { pd = new PropertyDescriptor(FieldName, o.getClass()); Method getMethod = pd.getReadMethod();//获得get方法 resultO = getMethod.invoke(o);//执行get方法返回一个Object } catch (Exception e) { e.printStackTrace(); } return resultO; }
解释示例:
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class TestPropertyDescriptor {
public static void main(String[] args) {
Person person = new Person();
person.setName("zhangsan");
person.setAge(18);
getFiled(person, "name");//结果输出 zhangsan
}
// 通过反射得到name
// 可以看到这是通过 得到 属性的get方法(pd.getReadMethod()) 再调用invole方法取出对应的属性值
//同样得到set方法(pd.getWriteMethod())
private static void getFiled(Object object, String field) {
Class<? extends Object> clazz = object.getClass();
PropertyDescriptor pd = null;
Method getMethod = null;
try {
pd = new PropertyDescriptor(field, clazz);
if (null != pd) {
// 获取 这个 field 属性 的get方法
getMethod = pd.getReadMethod();
Object invoke = getMethod.invoke(object);
System.out.println(invoke);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}