反射技术实际是已经能够完全满足我们对javaBean的各种操作了,但是为了方便JDK还是为我们提供了一套操纵JavaBean的API,我们称这套API为内省操作(Introspector)
下面介绍两种JavaBean的内省操作
先定义个JavaBean类
public class userbean {
private int age;
private String name;
public userbean() {
super();
}
public userbean(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第一种简单内省
public class Introspector1 {
/*
* JavaBean的简单内省
*/
public static void main(String[] args) throws Exception {
userbean bean = new userbean(20, "w");
String propertyName = "name"; // 属性名
// JavaBean的set方法
String setValue = "wzl";
setProperties(propertyName, bean, setValue);
// JavaBean的get方法
getProperties(propertyName, bean);
}
private static void getProperties(String propertyName, Object bean)
throws Exception {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,
bean.getClass());
Method methodGet = pd.getReadMethod();
Object retVal = methodGet.invoke(bean);
System.out.println(retVal);
}
private static void setProperties(String propertyName, Object bean,
Object setValue) throws Exception {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,
bean.getClass());// 得到Javabean属性描述符
Method methodSet = pd.getWriteMethod();
methodSet.invoke(bean, setValue);
}
}
第二种复杂内省
public class Introspector2 {
/*
* JavaBean的复杂内省
*/
public static void main(String[] args) throws Exception {
userbean bean = new userbean(20, "w");
String propertyName = "name"; // 属性名
// JavaBean的set方法
String setValue = "wzl";
setProperties(propertyName, bean, setValue);
// JavaBean的get方法
getProperties(propertyName, bean);
}
private static void getProperties(String propertyName, Object bean)
throws Exception {
// 把一个Java类当作JavaBean来看
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
// 得到所有的属性描述
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
Object retVal = new Object();
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals(propertyName)) {
Method methodGet = pd.getReadMethod();
retVal = methodGet.invoke(bean);
}
}
System.out.println(retVal);
}
private static void setProperties(String propertyName, Object bean,
Object setValue) throws Exception {
// 把一个Java类当作JavaBean来看
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
// 得到所有属性描述
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getName().equals(propertyName)) {
Method methodSet = pd.getWriteMethod();
methodSet.invoke(bean, setValue);
}
}
}
}