package testPoi;
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方法()
private static void getField(Object object, String field) {
Class<? extends Object> clazz = object.getClass();
PropertyDescriptor pd = null;
Method getMethod = null;
Method setMethod = null;
try {
pd = new PropertyDescriptor(field, clazz);
if (null != pd) {
// 获取field属性的get方法
getMethod = pd.getReadMethod();
Object getInvoke = getMethod.invoke(object);
// 获取field属性的set方法
setMethod= pd.getWriteMethod();
Object setInvoke = setMethod.invoke(object,"123");
System.out.println(setInvoke+ getInvoke);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
一个简单的PropertyDescriptor类的例子
最新推荐文章于 2025-03-20 00:29:36 发布