内省操作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());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值