您的位置:首页 > 编程语言 > Java开发

对JavaBean的内省操作——综合案例

2018-01-29 00:00 375 查看

一、概述

1、直接new一个PropertyDescriptor对象的方式来让大家了解JavaBean API的价值,先用一段代码读取JavaBean的属性,然后再用一段代码设置JavaBean的属性(方式1)(推荐)
2、用eclipse将读取属性和设置属性的流水帐代码分别抽取成方法

① 只要调用这个方法,并给这个方法传递了一个对象、属性名和设置值,它就能完成属性修改的功能

② 得到BeanInfo最好采用“obj.getClass()”方式,而不要采用“类名.class”方式,这样程序更通用

3、采用遍历BeanInfo的所有属性方式来查找和设置某个RefectPoint对象的x属性。在程序中把一个类当作JavaBean来看,就是调用IntroSpector.getBeanInfo方法, 得到的BeanInfo对象封装了把这个类当作JavaBean看的结果信息。(方式2)

二、代码说明

IntroSpectorTest.java

package staticimport.reflect.introspector;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/***
*
* 对JavaBean的简单内省操作
*
* @author Liu
*
*/
public class IntroSpectorTest {

public static void main(String[] args) throws Exception {
ReflectPoint reflectPoint = new ReflectPoint(3,4);

String propertyName = "xaxis";

Object retVal = getProperty(reflectPoint, propertyName);

System.out.println(retVal);

Object val = 10;

setProperty(reflectPoint, propertyName, val);

System.out.println(reflectPoint.getXaxis());

}

//调用JavaBean的api设置属性值
private static void setProperty(ReflectPoint reflectPoint, String propertyName, Object val)
throws IntrospectionException, IllegalAccessException, InvocationTargetException {
PropertyDescriptor propertyDescriptor2 = new PropertyDescriptor(propertyName, reflectPoint.getClass());
Method methodSet = propertyDescriptor2.getWriteMethod();
methodSet.invoke(reflectPoint,val);
}

//调用JavaBean的api读取属性值
private static Object getProperty(Object obj, String propertyName)
throws IntrospectionException, IllegalAccessException, InvocationTargetException {

//快速简洁方式
/*PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, obj.getClass());
Method methodGet = propertyDescriptor.getReadMethod();
Object retVal = methodGet.invoke(obj);
return retVal;*/

//复杂方式(采用遍历BeanInfo的所有属性方式来查找和设置某个RefectPoint对象的x属性)
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

for(PropertyDescriptor propertyDescriptor : propertyDescriptors){
if(propertyDescriptor.getName().equals(propertyName)){
return propertyDescriptor.getReadMethod().invoke(obj);
}
}

return null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java反射 内省 JavaBean