内省是一种特殊的反射,是反射机制的一个子集,是更加专业的操作字段的方法。所有关于所有内省的操作,用反射都可以实现,只是比较麻烦而已。内省可以对指定类属性的get或者set方法,直接对类的属性进行操作。经常的用法应该是把客户端传来的表单数据直接存放到JavaBean对应的属性中去。
对于javaBean中字段和属性的说明,举例
public class Person {
private String name; //类的字段
private int age; //类的字段
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddr(){
}
}
只有字段有对应的get或者set方法,这个字段才能称之为属性。例子中addr虽然没有与之对应的字段定义,但addr也是这个类的一个属性。、
关于内省的api在包java.beans中。
获取指定类的所有属性名称
@Test
public void intorAllProperty() throws IntrospectionException, ClassNotFoundException {
BeanInfo beanInfo = Introspector.getBeanInfo(Class.forName("com.legend.j2se.introspector.Person"),Object.class);
PropertyDescriptor[] pd = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor p : pd) {
System.out.println(p.getName());
}
}
操作类的属性
@Test
public void intorProperty() throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Person p = new Person();
PropertyDescriptor pd = new PropertyDescriptor("age",Person.class); //直接new属性描述器
Method m1 = pd.getWriteMethod();
m1.invoke(p, 32);
Method m2 = pd.getReadMethod();
System.out.println(m2.invoke(p, null));
}
实际工程中一般都使用BeanUtils实现对JavaBean的操作,用BeanUtils来实现对JavaBean的属性进行赋值非常方便
Person p = new Person();
BeanUtils.setProperty(p,"name","legend");
用BeanUtils获取JavaBean的属性值
BeanUtils.getProperty(p, "name");
557




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



