package com.interview.introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class IntroSpector {
public static void main(String[] args){
//ID号 姓名 年龄
Person person = new Person(0001, "张三", 23);
//通过属性名操作set get方法
String propertyName = "name";
Object retVal = getProperty(person, propertyName);
System.out.println("通过get方法得到的值为:"+retVal);
setProperty(person , propertyName , "李四");
System.out.println("set方法后的值为:"+getProperty(person, propertyName));
}
/**
* 通过反射技术得到属性的get方法,并返回相应的值
* @param obj 要调用的对象
* @param propertyName 属性名
* @return 属性值
*/
private static Object getProperty(Object obj, String propertyName) {
Object retVal = null ;
try {
/**--------方法一 --------------**/
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, obj.getClass());
//得到get方法
Method readMethod = descriptor.getReadMethod();
//执行get方法得到值,提供相应的类以及要传递的字段值
retVal = readMethod.invoke(obj, null);
/**-----------方法二-------------- **/
//得到所有属性的descriptor
// PropertyDescriptor[] descriptors = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
// //遍历得到相应的descriptor
// for(PropertyDescriptor des : descriptors){
// if(des.getName().equals(propertyName)){
// Method readMethod = des.getReadMethod();
// retVal = readMethod.invoke(obj, null);
// break;
// }
// }
} catch (Exception e) {
System.out.println("属性值不存在!");
}
return retVal;
}
/**
* 通过属性名,利用反射技术,得到属性的set方法,来set新值
* @param obj 要调用的对象
* @param propertyName 属性名
* @param propertyValue 要设置的属性值
*/
private static void setProperty(Object obj, String propertyName, String propertyValue) {
try {
PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, obj.getClass());
//得到get方法
Method writeMethod = descriptor.getWriteMethod();
//执行get方法得到值,提供相应的类以及要传递的字段值
writeMethod.invoke(obj, propertyValue);
} catch (Exception e) {
System.out.println("属性值不存在!");
}
}
}
来自张孝祥老师---31_对JavaBean的复杂内省操作
最后介绍了BeanUtils, PropertyUtils工具包使用,但是只有在java se项目中能使用,java web 项目报错,不知道什么原因!!!
要引入的包为: