java内省操作类的属性
1.取得指定类的属性的方法
2.操作指定类的属性的方法
3.得到指定类的属性数据类型的方法
package com.ma.introspector; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.junit.Test; import com.ma.bean.Proson; /** * 内省操作类的属性 * @author ma * */ public class IntrospectorDemo1 { /** * 取得指定类的属性的方法 * @throws IntrospectionException * */ @Test public void test1() throws IntrospectionException{ //在 Java Bean 上进行内省,了解其所有属性、公开的方法和事件。 BeanInfo bi = Introspector.getBeanInfo(Proson.class); //得到类的所有属性,只要有setXxx(),getXxx()方法中的一个,就是属性 PropertyDescriptor[] pdArr = bi.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : pdArr) { System.out.println(propertyDescriptor.getName()); } } /** * 操作指定类的属性的方法 * @throws IntrospectionException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ @Test public void test2() throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Proson p = new Proson(); //得到要操作的属性 PropertyDescriptor pd = new PropertyDescriptor("name", Proson.class); //得到属性的操作方法,即写方法 Method method = pd.getWriteMethod(); //操作属性 method.invoke(p, "孙权"); //输出 Method readMethod = pd.getReadMethod(); String name = (String)readMethod.invoke(p, null); System.out.println(name); } /** * 得到指定类的属性数据类型的方法 * @throws IntrospectionException * */ @Test public void test3() throws IntrospectionException{ Proson p = new Proson(); //得到要操作的属性 PropertyDescriptor pd = new PropertyDescriptor("age", Proson.class); //得到属性的数据类型 Class<?> type = pd.getPropertyType(); System.out.println(type); } }
实体类Proson
package com.ma.bean; /** * 人的实体类 * @author ma * */ public class Proson { private int id; private String name; private int age; public Proson() { super(); } public Proson(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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 getAb(){ return null; } public int aa(){ return 1; } public void setUu(int uu){ System.out.println("这是setUu()方法"); } }