通过PropertyDescriptor反射进行字段名值的获取及设置

通过PropertyDescriptor反射进行字段名值的获取及设置/** *根据属性名获取对应的value *@paramfieldName *@paramobj *@return *@throwsException */privatestaticStringgetValueByFiled(StringfieldName,Objectobj)throwsException{  //属性扫描器

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

/**
 * 根据属性名获取对应的value
 * @param fieldName
 * @param obj
 * @return
 * @throws Exception
 */
private static String getValueByFiled(String fieldName,Object obj)throws Exception{

       //属性扫描器
        PropertyDescriptor pd = new PropertyDescriptor(fieldName, obj.getClass());
        //从属性描述器中获取 get 方法
        Method method = pd.getReadMethod();
        //结果
        Object value = method.invoke(obj);
        //执行方法并返回结果
        return value==null?””:String.valueOf(value);
}

   

下面是比较完整的

public class PropertyUtil {  
    @SuppressWarnings("unchecked")  
    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方法  
               //构建get 方法  
               getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ });  
               //构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中  
               pd = new PropertyDescriptor(propertyName, getMethod, setMethod);  
            }  
        } catch (Exception ex) {  
                ex.printStackTrace();  
        }  
      
        return pd;  
    }  
    //对obj对象的指定字段进行值设置
    @SuppressWarnings("unchecked")  
    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();  
        }  
    }  
    
    //根据属性字段及对象获取对应的属性值	
    @SuppressWarnings("unchecked")  
    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;//返回值  
    }  
}  


//调用

import java.beans.PropertyDescriptor;  
import java.lang.reflect.Field;  
import java.lang.reflect.Method;  
public class ReflectTest {  
   
 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);  
  }  
 }  
}  

参考:http://blog.csdn.net/qq_34120041/article/details/53665526

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/187099.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Protostuff序列化和反序列化使用说明

    Protostuff序列化和反序列化使用说明google原生的protobuffer使用起来相当麻烦,首先要写.proto文件,然后编译.proto文件,生成对应的.java文件,鄙人试了一次,发现真的很麻烦。而protostuff的官方网站(http://www.protostuff.io/documentation/runtime-schema/),对于智商比较低的小编来说也略显生涩,于是鄙人就根据项目中用到的protostuff,撰写此文,以方便自己和他人加深印象和学习。

    2022年6月17日
    35
  • Http报头Accept与Content-Type的区别

    Http报头Accept与Content-Type的区别RequestMapping有多个属性来进一步匹配HTTP请求到Controller方法,分别是value,请求的URL的路径,支持也模板、正则表达式method,HTTP请求方法,有GETPOSTPUTconsumes,允许的媒体类型(MediaTypes),如onsumesapplication/ison”,对应于请求的HTTPConten…

    2022年8月24日
    6
  • 【python表白神器】手把手教你用代码浪漫追求对象!(附完整源码+讲解)

    【python表白神器】手把手教你用代码浪漫追求对象!(附完整源码+讲解)文章目录前言演示网站制作部署网站二维码制作总结前言跟着我做,不要跳着看,否则你会失败。第一步是制作二维码;第二步是制作网站。演示具体成果地址:https://yanghanwen.xyz/ai/网站制作首先你需要下载我的这个完整项目:链接:https://pan.baidu.com/s/1EmRehx_gRnT5hLjJvKuAIg提取码:pz1y–来自百度网盘超级会员V2的分享下载好后文件目录如下:然后你需要注意的是我把img里面的图片删了,涉及隐私,大家自己替换自己追

    2022年10月15日
    2
  • mnist手写数字识别代码_数字识别

    mnist手写数字识别代码_数字识别MNIST手写数字识别模型建立与优化本篇的主要内容有:TensorFlow处理MNIST数据集的基本操作建立一个基础的识别模型介绍SoftmaxSoftmaxSoftmax回归以及交叉熵等MNIST是一个很有名的手写数字识别数据集(基本可以算是“HelloWorld”级别的了吧),我们要了解的情况是,对于每张图片,存储的方式是一个28*28的矩阵,但是我们在导入数据进…

    2022年9月14日
    6
  • python之意外发现turtle的强大

    python之意外发现turtle的强大闲来无事,上网闲逛,无意中发现了turtle这个库,于是各种百度去了解,才知道这库niubi啊,居然可以画画!!!!1、turtle安装python3的话直接输入pipinstallturtle哈哈,是不是报错:Command“pythonsetup.pyegg_info”failedwitherrorcode1这是因为setup.py中有个语法在python3不…

    2022年6月24日
    30
  • ios分发平台搭建_app分发下载

    ios分发平台搭建_app分发下载iOS的内侧包管理,内部分发,或者企业包的分发和Android略有不同,需要通过manifest文件以及Safari内置命令来触发安装。

    2025年5月26日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号