1 开发框架时候,经常要对类属性进行赋值和取值,用反射完成过于繁琐,所以出现了内省API专门用来操作Bean类的属性,因为操作属性主要通过get和set方法,所以操作的是JavaBean类。
public testIntrospection() throws IntrospectionException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
User st = new User();
// 获取User.class的所有属性
PropertyDescriptor pdrs[] = Introspector.getBeanInfo(User.class)
.getPropertyDescriptors();
for (PropertyDescriptor pd : pdrs) {
System.out.println("属性" + pd.getName());
if (pd.getName().equals("age")) {
Method md = pd.getWriteMethod();// 获取set方法
md.invoke(st, 12);
md = pd.getReadMethod();// 获取get方法
System.out.println(md.invoke(st));
System.out.println(pd.getPropertyType());
}
}
}
它需要引入包:
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
打印:
属性adult
属性age
12
int
属性class
属性name
属性sex
说明:因为自带getClass方法,所以有class这属性
User.class的属性:
private String name;
private int age;
private boolean sex;
private boolean isAdult;
2 由于内省API过于繁琐,所以Apache组织开发了一套简单、易用的API操作Bean的工具包,BeanUtils。
public testBeanUtil() throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
// 获取到bean对象
User user = (User) Class.forName("test0917.User").newInstance();
// 采用BeanUtils对bean对象的属性做各种操作
BeanUtils.setProperty(user, "name", "xixiaoming");
System.out.println(BeanUtils.getProperty(user, "name"));
}
它需要引入的包:
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
打印:
xixiaoming
---------------------------------------------------------------------------------------------------------------
现在发送在CSDN上的文章都能在手机端查看啦,走路上班、闲暇之余可以看看手机,共勉共进!