无意间看到了内省,与反射相关联,所以写了一点操作
一个类有两种状态(编译和运行),通常我们是在编译状态来获取类的信息,也就是new一个实例出来然后通过该实例来获取类内部的信息。若需要在类运行时动态的获取类的信息,则需要用到反射
内省是通过反射来实现的,用BeanInfo来暴露一个bean的属性、方法和事件,以后我们就可以操纵该JavaBean的属性,其包括的主要类有:Introspector、BeanInfo、PropertyDescriptor
public class User {
private int id;
private String name;
private String eamil;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEamil() {
return eamil;
}
public void setEamil(String eamil) {
this.eamil = eamil;
}
public User(int id, String name, String eamil) {
super();
this.id = id;
this.name = name;
this.eamil = eamil;
}
}
public class test {
public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Introspector有方法来了解目标Java Bean支持的属性,事件和方法
// BeanInfo提供bean的方法,属性,事件和其他功能的显式信息
// PropertyDescriptor可导出一个属性
User user = new User(1,"Howl","11111111@qq.com");
// Introspector内有静态方法获取beanInfo,参数表示去除父类Object的方法,只保存User内部的方法
BeanInfo beanInfo = Introspector.getBeanInfo(User.class, Object.class);
// beanInfo内部有方法获取PropertyDescriptor
PropertyDescriptor[] propertys = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor value : propertys){
// 全部属性,名字,类型,可读,可写方法
System.out.println(value);
// 通过PropertyDescriptor获取读方法,也有写方法
Method method = value.getReadMethod();
System.out.println(method.invoke(user));
}
}
}
原文:https://www.cnblogs.com/Howlet/p/12349139.html