1 import java.beans.BeanInfo; 2 import java.beans.IntrospectionException; 3 import java.beans.Introspector; 4 import java.beans.PropertyDescriptor; 5 import java.lang.reflect.Method; 6 7 import org.junit.Test; 8 9 //使用内省api操作bean的属性 10 public class Demo { 11 12 /** 13 * 14 * @throws Exception 15 * 16 */ 17 //得到bean的所有属性 18 @Test 19 public void test1() throws Exception{ 20 BeanInfo info = Introspector.getBeanInfo(Person.class,Object.class); 21 22 PropertyDescriptor[] pds = info.getPropertyDescriptors(); 23 24 for(PropertyDescriptor pd : pds){ 25 System.out.println(pd.getName()); 26 } 27 } 28 29 //操纵bean的指定属性:age 30 @Test 31 public void test2() throws Exception{ 32 33 Person p = new Person(); 34 35 PropertyDescriptor pd = new PropertyDescriptor("age", Person.class); 36 37 //得到属性的写方法,为属性复制 38 Method method = pd.getWriteMethod();//public void setAge(){} 39 40 method.invoke(p, 32); 41 42 //获取属性的值 43 method = pd.getReadMethod();//public void getAge(){} 44 System.out.println(method.invoke(p, null)); 45 46 47 } 48 49 //高级点的内容,获取当前操作属性的类型 50 @Test 51 public void test3() throws Exception{ 52 53 Person p = new Person(); 54 55 PropertyDescriptor pd = new PropertyDescriptor("age", Person.class); 56 57 System.out.println(pd.getPropertyType()); 58 } 59 60 61 }
1 public class Person {// javabean 2 3 private String name; 4 private String password; 5 private int age; 6 7 public String getName() { 8 return name; 9 } 10 11 public void setName(String name) { 12 this.name = name; 13 } 14 15 public String getPassword() { 16 return password; 17 } 18 19 public void setPassword(String password) { 20 this.password = password; 21 } 22 23 public int getAge() { 24 return age; 25 } 26 27 public void setAge(int age) { 28 this.age = age; 29 } 30 31 public String getAb(){ 32 return null; 33 } 34 35 36 }
内省操作javabean的属性
时间: 2024-11-05 10:26:42