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多边形重心计算,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • SpringBoot实现application配置信息加密

    SpringBoot实现application配置信息加密

    在配置文件中,我们有开发环境配置和生产环境配置,而生产环境的配置信息是需要做好防护的,避免外泄,所以本文为大家整理了application配置信息加密的方法,需要的可以参考下
    2023-07-07
  • MyBatis中映射文件的使用案例代码

    MyBatis中映射文件的使用案例代码

    这篇文章主要介绍了MyBatis中映射文件的使用,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-02-02
  • 如何简单使用mybatis注解

    如何简单使用mybatis注解

    之前我们介绍了使用JDBC或者java框架mabatis来实现对数据库的操作,现在为了简化代码,提高程序的简洁性,我们探索如何使用注解进行开发,需要的朋友可以参考下
    2021-06-06
  • 一篇文章带你入门java模板模式

    一篇文章带你入门java模板模式

    这篇文章主要为大家详细介绍了java模板模式的相关资料,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • 五分钟带你了解Java的接口数据校验

    五分钟带你了解Java的接口数据校验

    这篇文章主要介绍了五分钟带你了解Java的接口数据校验,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • java实现简单的爬虫之今日头条

    java实现简单的爬虫之今日头条

    最近在学习搜索方面的东西,需要了解网络爬虫方面的知识,虽然有很多开源的强大的爬虫,但本着学习的态度,想到之前在做资讯站的时候需要用到爬虫来获取一些文章,今天刚好有空就研究了一下.在网上看到了一个demo,使用的是Jsoup,我拿过来修改了一下,有需要的朋友可以参考
    2016-11-11
  • java 微信随机红包算法代码实例

    java 微信随机红包算法代码实例

    这篇文章主要介绍了java 微信随机红包算法的相关资料,并附实例代码,需要的朋友可以参考下
    2016-10-10
  • java中有关构造方法中的输出

    java中有关构造方法中的输出

    这篇文章主要介绍了java中有关构造方法中的输出,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-10-10
  • spring 集成 mybatis的实例详解

    spring 集成 mybatis的实例详解

    这篇文章主要介绍了spring 集成 mybatis的实例详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-01-01

最新评论