内省机制和BeanUtils

1 开发框架时候,经常要对类属性进行赋值和取值,用反射完成过于繁琐,所以出现了内省API专门用来操作Bean类的属性,因为操作属性主要通过get和set方法,所以操作的是JavaBean类。
public testIntrospection() throws IntrospectionException,
		IllegalArgumentException, IllegalAccessException,
		InvocationTargetException {
	User st = new User();
	// 获取User.class的所有属性
	PropertyDescriptor pdrs[] = Introspector.getBeanInfo(User.class)
			.getPropertyDescriptors();
	for (PropertyDescriptor pd : pdrs) {
		System.out.println("属性" + pd.getName());
		if (pd.getName().equals("age")) {
			Method md = pd.getWriteMethod();// 获取set方法
			md.invoke(st, 12);
			md = pd.getReadMethod();// 获取get方法
			System.out.println(md.invoke(st));
			System.out.println(pd.getPropertyType());

		}
	}
}
它需要引入包:
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
打印:
属性adult
属性age
12
int
属性class
属性name
属性sex
说明:因为自带getClass方法,所以有class这属性
User.class的属性:
private String name;
private int age;
private boolean sex;
private boolean isAdult;
2 由于内省API过于繁琐,所以Apache组织开发了一套简单、易用的API操作Bean的工具包,BeanUtils。
public testBeanUtil() throws ClassNotFoundException,
		InstantiationException, IllegalAccessException,
		InvocationTargetException, NoSuchMethodException {
	// 获取到bean对象
	User user = (User) Class.forName("test0917.User").newInstance();
	// 采用BeanUtils对bean对象的属性做各种操作
	BeanUtils.setProperty(user, "name", "xixiaoming");
	System.out.println(BeanUtils.getProperty(user, "name"));
}
它需要引入的包:
import java.lang.reflect.InvocationTargetException;
import org.apache.commons.beanutils.BeanUtils;
打印:
xixiaoming

---------------------------------------------------------------------------------------------------------------
现在发送在CSDN上的文章都能在手机端查看啦,走路上班、闲暇之余可以看看手机,共勉共进!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值