美文网首页工作中用到的知识
Java中PropertyDescriptor使用以及问题总结

Java中PropertyDescriptor使用以及问题总结

作者: 幽澜先生 | 来源:发表于2019-01-28 17:27 被阅读0次

一、软件包 java.beans 

    包含与开发 beans 有关的类

二、PropertyDescriptor

    PropertyDescriptor 描述 Java Bean 通过存储器方法导出的一个属性

构造方法:

PropertyDescriptor(String propertyName, Class<?> beanClass)

PropertyDescriptor(String propertyName, Class<?> beanClass, String readMethodName, String writeMethodName)

PropertyDescriptor(String propertyName, Method readMethod, Method writeMethod)

常用方法:

public class PropertyDescriptor extends FeatureDescriptor 

    //构造方法 

    //通过调用 getFoo 和 setFoo 存取方法,为符合标准 Java 约定的属性构造一个 PropertyDescriptor 

    public PropertyDescriptor(String propertyName, 

                          Class<?> beanClass) 

                  throws IntrospectionException{} 

    //获得属性的 Class 对象 

    public Class<?> getPropertyType(){} 

    //获得应该用于读取属性值的方法 

    public Method getReadMethod(){} 

    //获得应该用于写入属性值的方法 

    public Method getWriteMethod(){} 

    ...

}

使用例子:

public class Price {

    private String mBuyPrice;

    public String getMBuyPrice() {

        return mBuyPrice;

    }

    public void setMBuyPrice(String mBuyPrice) {

        this.mBuyPrice = mBuyPrice;

    }

    @Override

    public String toString() {

        return "Price{" +

                "mBuyPrice='" + mBuyPrice + '\'' +

                '}';

    }

}

测试类:

public class TestPropertyDescriptor {

    public static void main(String[] args) {

        try {

            Class clazz = Class.forName("com.ssm.model.Price");

            Object obj =  clazz.newInstance();

            Field[] fields = clazz.getDeclaredFields();

            //写数据,即获得写方法(setter方法)给属性赋值

            for(Field f : fields){

                PropertyDescriptor pd = new PropertyDescriptor(f.getName(),clazz);

                Method method = pd.getWriteMethod();

                method.invoke(obj,"100元");

            }

            System.out.println(obj.toString());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

运行结果:

Price{mBuyPrice='100元'}

注意:

Price类中的属性为

private String mBuyPrice;

使用Idea或者Eclipse自动生成getter和setter方法时,会生成如下:

public class Price {

    private String mBuyPrice;

    public String getmBuyPrice() {

        return mBuyPrice;

    }

    public void setmBuyPrice(String mBuyPrice) {

        this.mBuyPrice = mBuyPrice;

    }

    @Override

    public String toString() {

        return "Price{" +

                "mBuyPrice='" + mBuyPrice + '\'' +

                '}';

    }

}

用测试类运行后会报错:

java.beans.IntrospectionException: Method not found: isMBuyPrice

同时Price类必须含有getter和setter方法,否则也会报同样的错误。

JavaBean属性名要求:前两个字母要么都大写,要么都小写

mport java.beans.PropertyDescriptor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

/**

* @author hui

* @description

* @create 2018/8/30 上午11:29

*/

public class PropertyDescriptorUtil {

    public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {

        StringBuffer sb = new StringBuffer();//构建一个可变字符串用来构建方法名称

        Method setMethod = null;

        Method getMethod = null;

        PropertyDescriptor pd = null;

        try {

            Field f = clazz.getDeclaredField(propertyName);//根据字段名来获取字段

            if (f != null) {

                //构建方法的后缀

                String methodEnd = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);

                sb.append("set" + methodEnd);

                //构建set方法

                setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{f.getType()});

                sb.delete(0, sb.length());

                sb.append("get" + methodEnd);

                //构建get 方法

                getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{});

                //构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中

                pd = new PropertyDescriptor(propertyName, getMethod, setMethod);

            }

        } catch (Exception ex) {

            ex.printStackTrace();

        }

        return pd;

    }

    public static void setProperty(Object obj, String propertyName, Object value) {

        Class clazz = obj.getClass();//获取对象的类型

        PropertyDescriptor pd = getPropertyDescriptor(clazz, propertyName);//获取 clazz 类型中的 propertyName 的属性描述器

        Method setMethod = pd.getWriteMethod();//从属性描述器中获取 set 方法

        try {

            setMethod.invoke(obj, new Object[]{value});//调用 set 方法将传入的value值保存属性中去

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    public static Object getProperty(Object obj, String propertyName) {

        Class clazz = obj.getClass();//获取对象的类型

        PropertyDescriptor pd = getPropertyDescriptor(clazz, propertyName);//获取 clazz 类型中的 propertyName 的属性描述器

        Method getMethod = pd.getReadMethod();//从属性描述器中获取 get 方法

        Object value = null;

        try {

            value = getMethod.invoke(clazz, new Object[]{});//调用方法获取方法的返回值

        } catch (Exception e) {

            e.printStackTrace();

        }

        return value;

    }

}

相关文章

网友评论

    本文标题:Java中PropertyDescriptor使用以及问题总结

    本文链接:https://www.haomeiwen.com/subject/tetzjqtx.html