内省(Introspector类)
内省的目标是得到JavaBean属性的读、写方法的反射对象,通过反射对JavaBean属性进行操作的一组API。
如下,有一个JavaBean
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
}
1.内省之获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(User.class);
2.得到所有属性描述符(PropertyDescriptor)
通过BeanInfo可以得到这个类的所有JavaBean属性的PropertyDescriptor对象。然后就可以通过PropertyDescriptor对象得到这个属性的getter/setter方法的Method对象了。
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
注:每个PropertyDescriptor对象对应一个JavaBean属性:
1) String getName():获取JavaBean属性名称;
2) Method getReadMethod:获取属性的读方法;
3) Method getWriteMethod:获取属性的写方法。
3.实例:完成Map数据封装到User对象中
public void fun1() throws Exception {
Map<String,String> map = new HashMap<String,String>();
map.put("username", "admin");
map.put("password", "admin123");
//获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(User.class);
//得到所有属性描述符
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//得到Javabean对象
User user = new User();
for(PropertyDescriptor pd : pds) {
String name = pd.getName();
String value = map.get(name);
if(value != null) {
Method writeMethod = pd.getWriteMethod();
//invoke(Object obj, Object... args)
对带有指定参数的指定对象调用由此 Method
对象表示的底层方法。
writeMethod.invoke(user, value);
}
}
System.out.println(user);
}
4.内省示意图