内省机制和BeanUtils
来源:互联网 发布:vb浏览文件夹选择txt 编辑:程序博客网 时间:2024/06/05 15:45
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上的文章都能在手机端查看啦,走路上班、闲暇之余可以看看手机,共勉共进!
- 内省机制和BeanUtils
- 内省和BeanUtils框架
- 内省(Introspector)和BeanUtils工具包
- 内省和BeanUtils框架2
- 内省和BeanUtils框架3
- 内省综合案例和 Beanutils 工具包
- 反射和内省机制
- 内省 BeanUtils框架
- 内省-----》javabean,以及BeanUtils
- Java 内省、JavaBean、BeanUtils
- Java 内省、JavaBean、BeanUtils
- 枚举&内省&beanutils
- 内省.BeanUtils操作JavaBean
- 日常小结-内省、beanutils
- junit测试、内省、BeanUtils
- Java高新技术之内省操作(BeanUtils、PropertyUtils和ConverUtils.register)
- 基础加强_JavaBean,反射和内省,BeanUtils工具
- 黑马程序员——javabean、内省和BeanUtils
- 【2084 数塔 DP】
- python实现汉字转拼音和读写excel
- 常用jar包之commons-beanutils使用
- java基础--Set, List和Map简介
- delphi Getclass findClass用法
- 内省机制和BeanUtils
- 初探coreText
- 解决Ulipad和有道词典冲突的问题
- 修改Ubuntu系统的时区时间日期和scim输入法的安装
- 容器vector的函数
- java poi 打开 excel 文件 保留格式 修改内容 另存为新文件
- 转:c# 根据当前时间获取,本周,本月,本季度,月初,月末,各个时间段
- 常用正则表达式大全!(例如:匹配中文、匹配html)
- maven中的 dependencies 和 dependencyManagement 的区别