一、Java内省介绍(Java内省操作JavaBean)
1、在做web开发的时候会大量用到JavaBean属性来封装数据,所以用Java内省操作节省了大量编码
2、JavaBean到底有什么属性,不由属性决定,由get 或 set 方法决定
3、可以用反射的方式操作JavaBean,但是JDK提供了 java.beans.*的API里提供了简便的对JavaBean的操作
4、在网上看作者博客文章,据说Struts封装Bean的属性的时候也用了Java的内省操作来实现的。
二、Java内省代码操作Student类
package com.java.a.introspector;
public class Student {
private String name;
private int luckyNum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLuckyNum() {
return luckyNum;
}
public void setLuckyNum(int luckyNum) {
this.luckyNum = luckyNum;
}
}
package com.java.a.introspector;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;
/**
* Java内省操作JavaBean
* @author TS
*/
public class IIntrospector {
/**
* 获取传入JavaBean的所有属性,包含其父类属性
* @throws Exception
*/
@Test
public void test() throws Exception{
//传入要内省的Class对象,获取BeanInfo
BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
//通过BeanInfo获取属性描述器数组
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//获取Student所有的属性(继承父类属性:class,luckyNum,name)
for (PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
}
}
/**
* 获取传入JavaBean的所有属性,不包含其父类属性
* @throws Exception
*/
@Test
public void test1() throws Exception{
//始停止分析的基类的JavaBean属性
BeanInfo beanInfo = Introspector.getBeanInfo(Student.class,Object.class);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
//获取Student所有的属性(luckyNum,name),不获取Object父类的属性
for (PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
}
}
/**
* 获取传入的JavaBean的指定属性
* @throws Exception
*/
@Test
public void test2() throws Exception{
Student s = new Student();
//获取指定的Bean属性(字段)
PropertyDescriptor pd = new PropertyDescriptor("luckyNum", Student.class);
//获取属性的真实类型
System.out.println( pd.getPropertyType() );
//获取属性的写方法,为属性赋值
Method method = pd.getWriteMethod();
//调用set方法
method.invoke(s, 47);
System.out.println(s.getLuckyNum());
//调用读方法( getXX() )
Method method2 = pd.getReadMethod();
System.out.println( method2.invoke(s, null) );
}
}