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

作者:周XXXX 时间:2023-10-11 19:34:17 

本文实例为大家分享了PropertyDescriptor反射调用set和get方法,供大家参考,具体内容如下

第一段:


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

第二段:


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

第三段:


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);
}
}
}
标签:Java,PropertyDescriptor,反射
0
投稿

猜你喜欢

  • 深入理解Java设计模式之简单工厂模式

    2023-12-06 07:16:36
  • Java实战之实现用户登录

    2022-08-03 14:42:55
  • Android CountDownTimer实现定时器和倒计时效果

    2023-12-09 02:11:28
  • Java设计模式之java备忘录模式详解

    2023-08-22 19:31:07
  • Android 新闻界面模拟ListView和ViewPager的应用

    2022-09-19 09:41:46
  • Java实现将png格式图片转换成jpg格式图片的方法【测试可用】

    2023-09-30 08:00:22
  • android使用Path绘制出多边形

    2021-11-11 19:53:38
  • springboot+mybatis-plus 两种方式打印sql语句的方法

    2022-12-29 13:41:11
  • Fastjson 常用API介绍及下载地址(推荐)

    2023-03-18 23:48:47
  • JavaWeb之Filter过滤器详解

    2021-06-30 03:40:55
  • 如何将C语言代码转换为应用程序(也就是编译)

    2022-09-02 06:30:49
  • C#使用foreach语句遍历队列(Queue)的方法

    2021-09-01 04:45:01
  • C#基于HttpWebRequest实现发送HTTP请求的方法分析

    2022-01-04 22:51:03
  • SpringBoot集成FTP与SFTP连接池流程

    2021-12-27 12:22:26
  • 通过实例解析Spring Ioc项目实现过程

    2023-11-24 10:12:33
  • Android硬件解码组件MediaCodec使用教程

    2023-03-14 01:35:36
  • Java定时器Timer简述

    2023-07-20 19:17:16
  • springboot-mybatis/JPA流式查询的多种实现方式

    2021-07-07 17:25:51
  • java GUI编程之监听操作实例分析

    2022-09-28 05:55:53
  • Android利用手势完成屏幕密码锁功能

    2023-04-08 21:21:40
  • asp之家 软件编程 m.aspxhome.com