内省 操作javabean的属性

来源:互联网 发布:淘宝全球购是正品吗 编辑:程序博客网 时间:2024/05/02 04:21
package com.lan.introspector;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.PropertyDescriptor;import java.lang.reflect.Method;import org.junit.Test;public class Demo {//得到bean的所有属性@Testpublic void test1() throws Exception {BeanInfo info = Introspector.getBeanInfo(Person.class,Object.class);PropertyDescriptor[] pds = info.getPropertyDescriptors();for(PropertyDescriptor pd : pds){System.out.println(pd.getName());}}//操纵bean的指定属性age@Testpublic void test2() throws Exception {Person person = new Person();PropertyDescriptor pDescriptor = new PropertyDescriptor("age", Person.class);//得到属性的写方法,为属性赋值.这里是setAge()Method method = pDescriptor.getWriteMethod();method.invoke(person, 30);System.out.println(person.getAge());//得到属性的读方法,为属性赋值.这里是getAge()Method method2 = pDescriptor.getReadMethod();Object object = method2.invoke(person, null);int age = (Integer) object;System.out.println(age); //System.out.println(method2.invoke(person,null);} //获取当前操作的属性类型            @Testpublic void test3() throws Exception {Person person = new Person();PropertyDescriptor pDescriptor = new PropertyDescriptor("name", Person.class);System.out.println(pDescriptor.getPropertyType());}}

package com.lan.introspector;//javabeanpublic class Person {private String name;private String password;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

原创粉丝点击