主要使用到了java.beans包下的類,利用底層反射來獲取對象對應的屬性和方法;
** BeanInfo **:提供有關Bean的顯式信息的接口,其中包含類的屬性,方法、事件等顯式信息,可以通過Introspector底層反射機制獲取
** Introspector **:用于構建一個一個全面描述目標bean的BeanInfo對象,使用低層次的反射來研究類的方法,并應用標準設計模式來標識屬性存儲器、事件源或公共方法。然后深入分析類的超類,并從它那里添加信息
** PropertyDescriptor ** :描述 Java Bean 通過一對存儲器方法導出的一個屬性以及該屬性的getter和setter方法
相關實現代碼:
public void test(Project project){
BeanInfo beanInfo;
try{
//throws IntrospectionException
beanInfo=Introspector.getBeanInfo(project.getClass(), Object.class);
if(beanInfo!=null){
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor p:propertyDescriptors){
//獲得屬性名稱
System.err.println(p.getName());
//調用該屬性名稱對應的getter方法
//throws IntrospectionException,InvocationTargetException,IllegalAccessException
Object obj = new PropertyDescriptor(p.getName(), Project.class).getReadMethod().invoke(project);
//調用該屬性名稱對應的setter方法
//throws IntrospectionException,InvocationTargetException,IllegalAccessException
new PropertyDescriptor(p.getName(), Project.class).getWriteMethod().invoke(project,new Object[]{"1"});
}
}
}catch (IntrospectionException e){
}catch (InvocationTargetException e1){
}catch (IllegalAccessException e2){
}