通过PropertyDescriptor和Introspector对JavaBean的简单内省操作

来源:互联网 发布:人工智能计算器破解 编辑:程序博客网 时间:2024/05/29 02:33
</pre><pre name="code" class="java">package com.franky.bean;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;/** * @描述 利用PropertyDescriptor类或Introspector类 *  进行javabean的内省操作,获取读写方法 * @作者 franky * @日期 2014-12-31 上午11:16:35 */public class JavaBeanTest {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {Point point = new Point(4, 5);String propertyName = "x";//按照javabean的方式来对对象进行内省操作//获取读的方法Object retVal = getReadMethod(point, propertyName);//另一种获取读的方法Object retVals = getReadMethod2(point, propertyName);System.out.println(retVal);//获取写的方法,并设置值Object value = 9;getWriteMethod(point, propertyName, value);System.out.println(point.getX());}/** * 获取bean对象的写方法,并修改值 * @param obj 内省javabean对象 * @param propertyName 属性名 * @param value 传入要修改的值对象 */private static void getWriteMethod(Object obj, String propertyName,Object value) throws IntrospectionException,IllegalAccessException, InvocationTargetException {PropertyDescriptor property2 = new PropertyDescriptor(propertyName , obj.getClass());Method writeMethod = property2.getWriteMethod();writeMethod.invoke(obj, value);}/** * 获取bean对象的读方法,并返回属性的值 * @param obj 内省javabean对象 * @param propertyName 属性名 * @return 返回属性值 */private static Object getReadMethod(Object obj, String propertyName)throws IntrospectionException, IllegalAccessException,InvocationTargetException {PropertyDescriptor property = new PropertyDescriptor(propertyName , obj.getClass());Method readMethod = property.getReadMethod();Object retVal = readMethod.invoke(obj, null);return retVal;}/** * 另一种获取bean对象的读方法,并返回属性的值 * @param obj 内省javabean对象 * @param propertyName 属性名 * @return 返回属性值 */private static Object getReadMethod2(Object obj, String propertyName)throws IntrospectionException, IllegalAccessException,InvocationTargetException {Object retVal = null; BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();for (int i = 0; i < descriptors.length; i++) {if(propertyName.equals(descriptors[i].getName())){Method readMethod = descriptors[i].getReadMethod();retVal = readMethod.invoke(obj, null);}}return retVal;}}

Point类:

package com.franky.bean;public class Point {private int x;private int y;/** * @return the x */public int getX() {return x;}/** * @param x the x to set */public void setX(int x) {this.x = x;}/** * @return the y */public int getY() {return y;}/** * @param y the y to set */public void setY(int y) {this.y = y;}public Point(int x, int y) {super();this.x = x;this.y = y;}}


0 0
原创粉丝点击