您的位置:首页 > 编程语言 > Java开发

内省操作JavaBean

2011-12-10 21:43 363 查看
package cn.zen.introspector;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import org.junit.Test;

import cn.zen.entity.Person;

public class Demo1 {
@Test
public void method1() throws Exception {
// BeanInfo bi = Introspector.getBeanInfo(Person.class);
BeanInfo bi = Introspector.getBeanInfo(Person.class, Object.class);
PropertyDescriptor pds[] = bi.getPropertyDescriptors();

for (PropertyDescriptor pd : pds) {
System.out.println(pd.getName());
}
}

@Test
public void method2() throws Exception {
Class clazz = Class.forName("cn.zen.entity.Person");
// Constructor c = clazz.getConstructor(null);
// Person p = (Person) c.newInstance(null);
Person p = (Person) clazz.newInstance();

PropertyDescriptor pd = new PropertyDescriptor("_Name", p.getClass());

Method method = pd.getWriteMethod();
method.invoke(p, "xiaopianzi");

method = pd.getReadMethod();
System.out.println(method.invoke(p, null));
}

@Test
public void method3() throws Exception {
Class clazz = Class.forName("cn.zen.entity.Person");
// Constructor c = clazz.getConstructor(null);
// Person p = (Person) c.newInstance(null);
Person p = (Person) clazz.newInstance();

PropertyDescriptor pd = new PropertyDescriptor("_Age", p.getClass());
System.out.println(pd.getPropertyType());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: