Java中PropertyDescriptor的用法及说明

 更新时间:2023年07月07日 08:40:10   作者:bboyzqh  
这篇文章主要介绍了Java中PropertyDescriptor的用法及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Java中PropertyDescriptor用法

PropertyDescriptor 类表示 JavaBean 类通过存储器导出一个属性。

构造方法有

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

常用方法有

Class<?> getPropertyType() // 获取属性的java类型对象
Method getReadMethod() // 获得用于读取属性值的方法
Method getWriteMethod() // 获得用于写入属性值的方法
void setReadMethod(Method readMethod) // Sets the method that should be used to read the property value.
void setWriteMethod(Method writeMethod) //Sets the method that should be used to write the property value.

用法:

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * Created by zhuqiuhui on 2017/11/15.
 */
public class PropertyUtil {
    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;
    }
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名
        Object obj = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        //写数据
        for (Field f : fields) {
            PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
            Method wM = pd.getWriteMethod();//获得写方法
            wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型
        }
        //读数据
        for (Field f : fields) {
            PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
            Method rM = pd.getReadMethod();//获得读方法
            Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印
            System.out.println(num);
        }
    }
}

Java PropertyDescriptor分析

简单说明

正如其名称,用于描述属性相关的信息,如对于读写方法的设置和读取,获取属性的类型等操作。

源码

public构造方法

public PropertyDescriptor(String propertyName, // 属性的名称
                        Class<?> beanClass // bean的class类型
                            )
public PropertyDescriptor(String propertyName, // 属性名称
                        Class<?> beanClass, // bean的class类型 
                        String readMethodName, // 读方法名称
                        String writeMethodName // 写方法名称
                        )
public PropertyDescriptor(String propertyName, // 属性名称
                        Method readMethod, // 读方法
                        Method writeMethod // 写方法
                        )

主要方法

// 获取属性的类型
public synchronized Class<?> getPropertyType() {}
// 获取读方法
public synchronized Method getReadMethod() {}
// 设置读方法
public synchronized void setReadMethod(Method readMethod) {}
// 获取读方法
public synchronized Method getWriteMethod() {}
// 设置读方法
public synchronized void setWriteMethod(Method writeMethod){}
// 设置属性可以使用的属性编辑器类型
public void setPropertyEditorClass(Class<?> propertyEditorClass) {}
// 获取当前设置的属性编辑器类型
public Class<?> getPropertyEditorClass() {}
// 创建bean对象对当前属性的属性编辑器
public PropertyEditor createPropertyEditor(Object bean) {}

例子

自定义属性编辑器

/**
 * 自定义的属性编辑器,转换数据类型
 */
public class MyAgePropertyEditor extends PropertyEditorSupport {
    private String sourceText;
    /**
     * 设置源数据值
     * @param text
     * @throws IllegalArgumentException
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        this.sourceText = text;
    }
    /**
     * 转换为满足age属性要求的int类型
     * @return
     */
    @Override
    public Object getValue() {
        return Integer.valueOf(sourceText);
    }
}

定义bean

public class BeanForPropertyDescriptor {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

测试代码

public class MainForPropertyDescriptor {
    public static void main(String[] args) throws Exception {
        Class<BeanForPropertyDescriptor> beanForPropertyDescriptorClass
                = BeanForPropertyDescriptor.class;
        PropertyDescriptor agePropDescriptor
                = new PropertyDescriptor("age", beanForPropertyDescriptorClass);
        Method readMethod = agePropDescriptor.getReadMethod();
        System.out.println("读方法是:");
        System.out.println(readMethod);
        Method writeMethod = agePropDescriptor.getWriteMethod();
        System.out.println("写方法是:");
        System.out.println(writeMethod);
        // 设置属性编辑器,用来修改属性
        agePropDescriptor.setPropertyEditorClass(MyAgePropertyEditor.class);
        BeanForPropertyDescriptor beanForPropertyDescriptor = new BeanForPropertyDescriptor();
        PropertyEditor agePropertyEditor = agePropDescriptor.createPropertyEditor(beanForPropertyDescriptor);
        agePropertyEditor.setAsText("90");
        Object value = agePropertyEditor.getValue();
        System.out.println(value.getClass());
    }
}

运行:

读方法是:
public int yudaosourcecode.propertydescriptortest.BeanForPropertyDescriptor.getAge()
写方法是:
public void yudaosourcecode.propertydescriptortest.BeanForPropertyDescriptor.setAge(int)
class java.lang.Integer

Process finished with exit code 0

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java中死锁的原理实战分析

    Java中死锁的原理实战分析

    这篇文章主要介绍了Java中死锁的原理,结合具体案例形式分析了java死锁形成的相关原理,需要的朋友可以参考下
    2019-08-08
  • Java String类的常用方法汇总

    Java String类的常用方法汇总

    这篇文章主要为大家详细汇总了Java String类的常用方法,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • Idea 2020.2 创建web、Spring项目的教程图解

    Idea 2020.2 创建web、Spring项目的教程图解

    这篇文章主要介绍了Idea 2020.2 创建web、Spring项目的教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • IntelliJ IDEA创建maven web项目的图文步骤(IDEA新手适用)

    IntelliJ IDEA创建maven web项目的图文步骤(IDEA新手适用)

    这篇文章主要介绍了IntelliJ IDEA创建maven web项目的图文步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • 使用maven整合Spring+SpringMVC+Mybatis框架详细步骤(图文)

    使用maven整合Spring+SpringMVC+Mybatis框架详细步骤(图文)

    这篇文章主要介绍了使用maven整合Spring+SpringMVC+Mybatis框架详细步骤(图文),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • Java this 关键字的使用方法详解

    Java this 关键字的使用方法详解

    这篇文章主要介绍了Java this 关键字的使用方法详解的相关资料,希望通过本文能帮助到大家,让大家彻底理解掌握这部分内容,需要的朋友可以参考下
    2017-10-10
  • Java去掉小数点后面无效0的方案与建议

    Java去掉小数点后面无效0的方案与建议

    当前小数点后面的位数过多的时候,多余的0没有实际意义,下面这篇文章主要给大家介绍了关于Java去掉小数点后面无效0的方案与建议,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-07-07
  • 在CentOS系统中检测Java安装及运行jar应用的方法

    在CentOS系统中检测Java安装及运行jar应用的方法

    这篇文章主要介绍了在CentOS系统中检测Java安装及运行jar应用的方法,同样适用于Fedora等其他RedHat系的Linux系统,需要的朋友可以参考下
    2015-06-06
  • java中处理socket通信过程中粘包的情况

    java中处理socket通信过程中粘包的情况

    本篇文章主要介绍了java中处理socket通信过程中粘包的情况,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-05-05
  • java中实体类转Json的2种方法

    java中实体类转Json的2种方法

    本篇文章中主要介绍了java中实体类转Json的2种方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧。
    2017-01-01

最新评论