通过PropertyDescriptor反映射调用set和get方法

通过PropertyDescriptor反映射调用set和get方法1packagecom.zhoushun;importjava.lang.reflect.Method;importjava.lang.reflect.Field;importjava.beans.PropertyDescriptor;publicclassPropertyUtil{ @SuppressWarnings(“unchecked”) publicsta

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

Jetbrains全系列IDE稳定放心使用

1

package com.zhoushun;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.beans.PropertyDescriptor;

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;
	}
	
	@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;//返回值
	}
}

2

public boolean setValue(Object objSet, Object objGet)
        throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, IntrospectionException
    {
        boolean flag = true;
        Field fields[] = objSet.getClass().getDeclaredFields();
        String value = "";
        String fieldNameGet = "";
        List list = new ArrayList();
        Field afield[];
        int j = (afield = fields).length;
        for(int i = 0; i < j; i++)
        {
            Field field = afield[i];
            String fieldName = field.getName();
            fieldNameGet = xmlToModel(fieldName);
            if(!"error".equals(fieldNameGet))
            {
                PropertyDescriptor pd = new PropertyDescriptor(fieldNameGet, objGet.getClass());
                Method getMethod = pd.getReadMethod();
                value = String.valueOf(getMethod.invoke(objGet, new Object[0]));
                boolean checkResult = returnMessage.checkValue(value, fieldNameGet);
                if(checkResult)
                {
                    PropertyDescriptor pd1 = new PropertyDescriptor(fieldName, objSet.getClass());
                    Method setMethod = pd1.getWriteMethod();
                    setMethod.invoke(objSet, new Object[] {
                        field.getType().getConstructor(new Class[] {
                            java/lang/String
                        }).newInstance(new Object[] {
                            value
                        })
                    });
                } else
                {
                    flag = checkResult;
                }
            }
        }


        return flag;
    }

3

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);
  }
 }
}

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

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

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


相关推荐

  • 10天学通Android开发(5)-项目实战:计算器

    10天学通Android开发(5)-项目实战:计算器

    2021年9月3日
    56
  • 腾讯七大事业群_腾讯pcg事业群难进吗

    腾讯七大事业群_腾讯pcg事业群难进吗企业发展事业群(CorporateDevelopmentGroup,简称CDG)意如其名,企业发展事业群CDG在腾讯内部担当战略规划、投资者关系维护、业务孵化和投资并购等角色。众所周知的微信、财付通、QQ邮箱等业务均属CDG,诸多投资工作也由CDG负责,比如国内外投资并购、海外市场推广等工作,有志于股权投资、创新业务、国际化并拥有专长的同学可格外关注!互动娱乐事业群(I

    2025年11月13日
    1
  • win10专业版虚拟机配置服务器,win10专业版怎么运行虚拟机_win10专业版开启虚拟机的方法…

    win10专业版虚拟机配置服务器,win10专业版怎么运行虚拟机_win10专业版开启虚拟机的方法…虚拟机大家应该都很熟悉吧 就是允许你在当前操作系统中运行其他操作系统 虚拟操作系统会像你电脑上的另一个程序一样运行 有 win10 专业版系统用户想要运行虚拟机 可是却不知要怎么操作 其实系统中自带有虚拟机功能 我们只要将其开启就可以了 接下来给大家分享一下 win10 专业版开启虚拟机的方法 具体步骤如下 1 首先要找到控制面板 我们点开 windows 键 然后选择在所有应用中找到 Windows 系统

    2025年8月1日
    6
  • Spark Streaming Join「建议收藏」

    Spark Streaming Join「建议收藏」多数据源Join思路多数据源Join大致有以下三种思路:数据源端Join,如Android/IOS客户端在上报用户行为数据时就获取并带上用户基础信息。计算引擎上Join,如用SparkStreaming、Flink做Join。结果端Join,如用HBase/ES做Join,Join键做Rowkey/_id,各字段分别写入列簇、列或field。三种思路各有优劣,使用时注意…

    2022年6月30日
    29
  • 2021 idea激活码最新(破解版激活)

    2021 idea激活码最新(破解版激活),https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月17日
    75
  • springboot框架图解_spring boot框架搭建

    springboot框架图解_spring boot框架搭建本文链接:https://blog.csdn.net/qq_41063141/article/details/83239941

    2022年8月20日
    6

发表回复

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

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