运用IntrosPector(内省)获取和操作javabean的属性
什么是javabean?
自省可以干什么?
我们在获取javabean的属性的时候通常用new对象的形式来调用,这种方法使得代码的通用性变得特别差,所以就得用内省,它的用途和反射差不多,都是提高代码的重用性,使得代码变得十分灵活。
要测试javabean
package TestIntrosPector;
public class People {
private int age;
private String name;
private char sex='女';
public People() {
super();
}
public People(int age, String name, char sex) {
super();
this.age = age;
this.name = name;
this.sex = sex;
}
public String getWaihao() {
return "我的外号是二狗"+name;
}
public int getAge() {
System.out.println("我的芳龄");
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
System.out.println("原名王尼玛");
return name;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
System.out.println("默认人妖");
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
}
自省工具类
package TestIntrosPector;
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;
public class IntrosPectorDemo {
public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//1.通过intropestor分析出字节码对象的信息beaninfo
BeanInfo bean=Introspector.getBeanInfo(People.class, Object.class);//左闭右开,过滤父类的benninfo
//2.通过调用getpro....方法获取对象的属性描述器
PropertyDescriptor[] pro=bean.getPropertyDescriptors();
for (PropertyDescriptor property : pro) {
String name=property.getName();//3.获取属性的名称,getname继承父类的方法
//4.得到属性的类型
System.out.println("属性类型:"+property.getPropertyType());
System.out.println("属性名字:"+name);
if(name.equals("waihao")) {
Method meth=property.getReadMethod();//获取读属性的方法get
Object obj=meth.invoke(new People());//执行对象的属性的get方法
System.out.println(obj);
}
System.out.println("获取属性的set方法"+property.getWriteMethod());//
System.out.println("获取属性的个体方法"+property.getReadMethod());//
System.out.println("--------------------");
}
}
}