Introspector (内省)是操作javaBean的属性API,用来访问某个属性的 getter/setter 方法。
什么事JavaBean?
1.具备空参构造。
2.提供熟悉的get/set方法。
3.属性对象变量实例化。
例如以下的JAVABEAN中
public class User {
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}我们可以通过User中的方法get,set来获得值和设置值。在jdk中提供了一套API用来访问某个熟悉的get/set方法。这就是JAVA的内省。
JDK内省类库
propertyDescriptor类
利用propertyDescriptor类,在其实例化的时候传入属性字符串和JAVABean。这样就能构造出一个PropertyDescriptor。利用PropertyDescriptor来获取javaBean的get/set方法。
public class propertyDescriptorTest {
public static void main(String[] args) throws Exception {
User u = new User();
setProperty(u, "name");
getProperty(u, "name");
}
/**
* 向指定的属性值中写入值
* @param user
* @param propertyName
* @throws Exception
*/
public static void setProperty(User user, String propertyName)
throws Exception {
PropertyDescriptor propertyDescriptor= new PropertyDescriptor(propertyName,
User.class);
Method methodSetUserName = propertyDescriptor.getWriteMethod();//获取set方法
methodSetUserName.invoke(user, "haha"); //调用set方法,并传入参数
System.out.println("setName:" + user.getName());
}
/**
* 从指定的属性值中获取值
* @param user
* @param propertyName
* @throws Exception
*/
public static void getProperty(User user, String propertyName)
throws Exception {
PropertyDescriptor propertyDescriptor= new PropertyDescriptor(propertyName,
User.class);
Method methodGetUserName = propertyDescriptor.getReadMethod(); //获取get方法
Object name = methodGetUserName.invoke(user);//调用get方法
System.out.println("getName:" + name.toString());
}
}
Introspector类
利用Introspector可以直接获取class的beanInfo.通过beanInfo获取JAVABean中所有的PropertyDescriptor。利用PropertyDescriptor获得get方法或set方法。
public class IntrospectorTest {
public static void main(String[] args) throws IntrospectionException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
User user = new User();
BeanInfo beanInfo = Introspector.getBeanInfo(User.class);
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();//获取PropertyDescriptor的数组
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
System.out.println(propertyDescriptor.getName());
if (propertyDescriptor.getName().equals("name")) {
Method writeMethod = propertyDescriptor.getWriteMethod();
writeMethod.invoke(user, "haha");
}
}
System.out.println(user.getName());
}
}以上是两种JAVA的内省,用于操作javabean的api。但是有没有想过一个问题,既然javabean已经有了get/set方法,为何还有利用内省去操作javabean。这里就涉及到了对java内省的应用。下一次会总结这一部分内容。
本文介绍了Java内省的概念及其应用,详细解析了如何使用propertyDescriptor类和Introspector类操作JavaBean的属性,包括获取和设置属性值。
1万+

被折叠的 条评论
为什么被折叠?



