package advance;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.BeanUtils;
public class IntroSpectorTest {
public static void main(String args[]) throws Exception{
ReflectEntity pt1 = new ReflectEntity(3,5);
String propertyName = "x";
// Object retVal = getProperty(pt1, propertyName);
// System.out.println(retVal);
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
Method methodSetX = pd2.getWriteMethod();
methodSetX.invoke(pt1,7);//invoke 表示调用这个方法执行,意思就是让invoke调用的这个方法执行,就是让setX方法执行,让作用于pt1这个对象上的setX方法执行,本身来讲setX没有返回值,所以“invoke调用这个方法==setX在执行”,本身setX没有返回值,所以这里就没有返回值,终于明白了
System.out.println(pt1.getX());
//加入操作JavaBean的工具包后,可以使用BeanUtils工具
System.out.println(BeanUtils.getProperty(pt1, "x").getClass().getName());
BeanUtils.setProperty(pt1, "x", "9");
System.out.println(pt1.getX());
}
private static Object getProperty(ReflectEntity pt1, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
/*得到属性的方法1
PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());把这个类当做javabean来看,然后再从这个JavaBean即1这里得到属性
Method methodGetX = pd.getReadMethod();
Object retVal = methodGetX.invoke(pt1);//invoke就是让methodGetX这个方法执行,其实说白了就是让getX这个方法执行,这个方法是作用于pt1对象上的,至于返回值,原来方法有返回值那么就有返回值,如果没有就没有,例如这里这个getX有返回值就是Object类型,老师说了,是类型提升了,
*/
//得到属性的方法2
BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = null;
for(PropertyDescriptor pd:pds){
if(pd.getName().equals(propertyName)){
Method methodGetX = pd.getReadMethod();//拿到JAVAbean的用于读取属性值的方法
retVal = methodGetX.invoke(pt1);
}
}
return retVal;
}
}
java中的反射
最新推荐文章于 2022-09-03 23:21:13 发布