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());
}
}
内省操作JavaBean
最新推荐文章于 2019-01-08 11:40:16 发布