- 创建包package cn.itccast.introspector,在包下建javabean类Student,代码如下:
package cn.itccast.introspector;
public class Student {
private String name;
private String password;
private String email;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 在包cn.itccast.introspector下建Demo类,操作Student类的属性
package cn.itccast.introspector;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;
public class Demo {
@Test
public void test() throws Exception{
PropertyDescriptor pd=new PropertyDescriptor("name", Student.class);
Method write=pd.getWriteMethod();
Student stu=new Student();
write.invoke(stu, "maomao");
Method reader=pd.getReadMethod();
String name=(String) reader.invoke(stu,null);
System.out.println(name);
}
@Test
public void test2() throws IntrospectionException{
BeanInfo bif=Introspector.getBeanInfo(Student.class);
PropertyDescriptor pds[]=bif.getPropertyDescriptors();
for(PropertyDescriptor pd: pds){
System.out.println(pd.getName());
}
}
}