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


相关推荐

  • ctf-web:关于文件上传漏洞的深入研究[通俗易懂]

    ctf-web:关于文件上传漏洞的深入研究[通俗易懂]上次我们研究了关于文件上传的漏洞,这次我们研究的内容属于上节课的补充内容,关于文件上传的绕过与防御.怎么说呢,算是一种锻炼吧.因为下个月有个awd的比赛,因此最近会经常发一些关于web的内容.其实我还是挺慌的,因为以前参加的都是ctf线上赛,而且我做的都是逆向这个方面的,然而这次突然来了个web,搞得我有点懵.web也是最近才开始研究的,所以写的可能不尽人意,希望各位大佬看看就好,不喜勿喷.一.实验环境我们这次的实验依然用的是上次的网站和phpstudy.我发在了下面.1.upload-f.

    2022年7月15日
    14
  • ubuntu安装rabbitvcs[通俗易懂]

    ubuntu安装rabbitvcs[通俗易懂]安装RabbitVCS的方法步骤如下:第一步:将rabbitvcs的添加到源里面。(次操作会提示是否要添加到源里面,点击ENTER添加,Ctrl+C不添加),这里选择ENTER方便更新。sudoadd-apt-repositoryppa:rabbitvcs/ppa第二步:根据第一步的情况来是否跳过该步骤,如果第一步出现导入key,那第二步可以跳过,否则需要导入keysudo

    2022年7月18日
    15
  • ExecuteNonQuery()_java有返回值和无返回值

    ExecuteNonQuery()_java有返回值和无返回值查询某个表中是否有数据的时候,我用了ExecuteNonQuery(),并通过判断值是否大于0来判断数据的存在与否。结果与我所设想的很不一致,调试时才发现,其执行后返回的结果是-1,对此我很是不理解,回头查了下资料,如下显示:SqlCommand.ExecuteNonQuery方法对连接执行Transact-SQL语句并返回受影响的行数。备注:可以使用ExecuteNonQuery来执行…

    2025年11月1日
    5
  • 第二次实验_第一次

    第二次实验_第一次第二次实验

    2022年4月21日
    45
  • Linux下历史命令(history)添加时间戳

    Linux下历史命令(history)添加时间戳

    2021年8月29日
    85
  • PhpStorm terminal无法输入命令的解决方法

    PhpStorm terminal无法输入命令的解决方法

    2021年10月20日
    40

发表回复

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

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