利用java反射机制一次性调用实体类get和set方法,简化更多代码。
外部调用getProperty方法时只需要传入实体对象即可;例如TestUtil.getProperty(new User());
外部调用setProperty方法时只需要传入实体对象和要set的值即可;例如TestUtil.setProperty(new User(), "setValue");
这里调用setProperty方法后User类中所有字段的值都将变为"setValue",所以这里想要给不同的字段set不同的值,则换一个参数
以下是核心工具类,
package com.qcp.test; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Field; public class TestUtil { /* 该方法用于传入某实例对象以及对象方法名,通过反射调用该对象的某个get方法 */ public static void getProperty(Object beanObj){ try { Field[] fields = beanObj.getClass().getDeclaredFields();//获得属性 Class clazz = beanObj.getClass(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; // 此处应该判断beanObj,property不为null PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); Method getMethod = pd.getReadMethod(); if (getMethod != null) { System.out.println(beanObj+"的字段是:"+field.getName()+",类型是:"+field.getType()+",取到的值是: "+getMethod.invoke(beanObj)); } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } } /* 该方法用于传入某实例对象以及对象方法名、修改值,通过放射调用该对象的某个set方法设置修改值 */ public static void setProperty(Object beanObj, Object value){ try { Field[] fields = beanObj.getClass().getDeclaredFields();//获得属性 Class clazz = beanObj.getClass(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; // 此处应该判断beanObj,property不为null PropertyDescriptor pd = new PropertyDescriptor(field.getName(), beanObj.getClass()); Method setMethod = pd.getWriteMethod(); if (setMethod != null) { System.out.println(beanObj+"的字段是:"+field.getName()+",参数类型是:"+field.getType()+",set的值是: "+value); //这里注意实体类中set方法中的参数类型,如果不是String类型则进行相对应的转换 setMethod.invoke(beanObj, value);//invoke是执行set方法 } } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?