通过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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • JavaScript实现哈希表数据结构[通俗易懂]

    一、简单说明1、JavaScript是没有哈希表数据结构的,那么当我们需要用到类似哈希表这样的键值对数据结构时怎么办?答案就是自己实现一个,我们可以利用JavaScript的一些特性来实现自己的哈希表数据结构。2、首先,哈希表是一种键值对数据结构,键是唯一的,这个特征跟JavaScript的Object对象有点类似,Object对象的属性是唯一的,属性和值的映射就像是键值对一样,那么我们可以用一个…

    2022年4月9日
    64
  • ubuntu中科大镜像源_中国科技大学开源镜像

    ubuntu中科大镜像源_中国科技大学开源镜像#vim/etc/apt/sources.list//修改网络镜像源文件debhttps://mirrors.ustc.edu.cn/ubuntu/bionicmainrestrict

    2022年8月2日
    37
  • L3-023 计算图(链式求导+bfs拓扑|dfs)「建议收藏」

    L3-023 计算图(链式求导+bfs拓扑|dfs)「建议收藏」原题链接“计算图”(computational graph)是现代深度学习系统的基础执行引擎,提供了一种表示任意数学表达式的方法,例如用有向无环图表示的神经网络。 图中的节点表示基本操作或输入变量,边表示节点之间的中间值的依赖性。 例如,下图就是一个函数 ( 的计算图。现在给定一个计算图,请你根据所有输入变量计算函数值及其偏导数(即梯度)。 例如,给定输入,,上述计算图获得函数值 (;并且根据微分链式法则,上图得到的梯度 ∇。知道你已经把微积分忘了,所以这里只要求你处理几个简单的算子:加法、减法、乘

    2022年8月8日
    12
  • 图论-树的最大路

    图论-树的最大路

    2021年11月29日
    41
  • String类型转int,转long

    String类型转int,转longStringstr1="123";Stringstr2="123.0";不带小数:可直接可转为intinta=Integer.parseInt(str);带小数,直接转为int会报数字格式化异常,需要先转为double,后转为int转int: intb=(int)Double.parseDouble(str);转long:longc =(lon…

    2022年6月5日
    36
  • python构建IP代理池(Proxy Pool)[通俗易懂]

    python构建IP代理池(Proxy Pool)[通俗易懂]基本原理代理实际上指的就是代理服务器,它的功能是代理网络用户去取得网络信息。也可以说它是网络信息的中转站。在我们正常请求一个网站时,是将请求发送给Web服务器,Web服务器把响应传回给我们。如果设置了代理服务器,实际上就是在本机和服务器之间搭建了一个桥,此时本机不是直接向Web服务器发起请求,而是向代理服务器发出请求,请求会发送给代理服务器,然后由代理服务器再发…

    2022年5月18日
    33

发表回复

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

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