`
375809600
  • 浏览: 150831 次
  • 来自: 湖北
社区版块
存档分类
最新评论

内省操作javabean

阅读更多
内省操作javabean,是反射的一种特殊形式,更简单的操作
//示例代码
package com.itcast.bean;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
private String grade;
private String age;

}
//测试类
package com.itcast.bean;

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 getAllProperty() throws Exception {// 用内省获得bean的所有属性
BeanInfo info = Introspector.getBeanInfo(Person.class);
PropertyDescriptor[] pds = info.getPropertyDescriptors();
for (int i = 0; i < pds.length; i++) {
System.out.println(pds[i].getName());
}
}
@Test
public void getNeed() throws Exception {// 获得指定的bean属性
Person p = new Person();
PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);//获得这个属性的所有信息
Method wrimethod = pd.getWriteMethod();//获得属性的写方法
wrimethod.invoke(p, "20");//执行写方法
Method redmethod = pd.getReadMethod();
System.out.println(redmethod.invoke(p));
}
@Test
public void switchType() throws Exception{//获得指定的参数的类型
PropertyDescriptor pd = new PropertyDescriptor("age", Person.class);
System.out.println(pd.getPropertyType());
}
}

0
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics