javabean是一种特殊的Java类,主要用于传递数据信息,这种类主要用于访问私有字段,且方法名符合某种规则,例如set + 私有变量名,get + 私有变量名这种成对的方法名。
javabean主要是通过PropertyDescriptor类反射得到字段,并用getReadMethod、getWriteMethod得到字段对应的读写方法,再调用该方法invoke取得值或设置值。
例子:
package pengesoft.sun.pack;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class JavaBeanTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Person ps = new Person(20, "张三");
//不适用内省的做法(也是反射):age->Age->getAge->取值
String propertyName = "age";
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, ps.getClass());
Method getValue = pd1.getReadMethod();
System.out.println(getValue.invoke(ps));
String propertyName1 = "name";
PropertyDescriptor pd2 = new PropertyDescriptor(propertyName1, ps.getClass());
Method setValue = pd2.getWriteMethod();
setValue.invoke(ps, "李四");
System.out.println(ps.getName());
}
}
class Person
{
public Person(int age, String name)
{
this.age = age;
this.name = name;
}
private int age;
private String 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;
}
}