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


相关推荐

  • 解决Centos/Redhat,命令不存在

    解决Centos/Redhat,命令不存在

    2022年2月23日
    59
  • k1145次列车经过站点_最小生成树和最短路径的区别

    k1145次列车经过站点_最小生成树和最短路径的区别北极的某区域共有 n 座村庄,每座村庄的坐标用一对整数 (x,y) 表示。为了加强联系,决定在村庄之间建立通讯网络,使每两座村庄之间都可以直接或间接通讯。通讯工具可以是无线电收发机,也可以是卫星设备。无线电收发机有多种不同型号,不同型号的无线电收发机有一个不同的参数 d,两座村庄之间的距离如果不超过 d,就可以用该型号的无线电收发机直接通讯,d 值越大的型号价格越贵。现在要先选择某一种型号的无线电收发机,然后统一给所有村庄配备,数量不限,但型号都是 相同的。配备卫星设备的两座村庄无论相距多远都可以直

    2022年8月10日
    4
  • java之Scanner详解「建议收藏」

    java之Scanner详解「建议收藏」1.包:importjava.util.Scanner2.使用方法:Scannerreader=newScanner(System.in);  然后reader对象调用下列方法(函数),读取用户在命令行输入的各种数据类型:   nextByte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),next

    2022年7月20日
    10
  • 如何判断一个数是否为素数(判断一个数为素数)

    目录1.什么是质数?2.如何判断是否为质数?方法1方法2方法3方法41.什么是质数?首先来看质数的概念:质数(Primenumber),又称素数,指在大于1的自然数中,除了1和该数自身外,无法被其他自然数整除的数。(也可定义为只有1与该数本身两个正因数的数)图1数字12不是质数,而数字11是质数如上图所示,数字12可以将每4个分成一组,…

    2022年4月18日
    41
  • 体验国产Linux系统,开局就翻车了…

    体验国产Linux系统,开局就翻车了…本文转载自差评,作者差评君可能你们之前在网上看到过别人对Linux操作系统的分析,也在新闻里见过有关国产Linux操作系统的报道。那么你们肯定也见过这些帖子下面的评论区里,不断有人复述着“垃圾”、“难用”。被称作“最美操作系统”的深度OS▼我相信,很多小伙伴是想尝试一下国产Linux操作系统的,但碍于现实条件往往只能作罢。所以,Linux真的难用吗;假如说从明天开始,Windows和苹果MacOS突然不能用了,Linux…

    2022年5月17日
    57
  • 常用网络图片url地址「建议收藏」

    常用网络图片url地址「建议收藏」http://www.baidu.com/img/bdlogo.pnghttp://rongcloud-web.qiniudn.com/docs_demo_rongcloud_logo.png

    2022年7月1日
    310

发表回复

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

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