利用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();
}
}
}







posted @   silentmuh  阅读(1217)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
Live2D
欢迎阅读『利用java反射机制一次性调用实体类get和set方法,简化更多代码。』
  1. 1 Walk Thru Fire Vicetone
  2. 2 爱你 王心凌
  3. 3 Inspire Capo Productions - Serenity
  4. 4 Welcome Home Radical Face
  5. 5 粉红色的回忆 李玲玉
Inspire - Capo Productions - Serenity
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

纯音乐,请欣赏

点击右上角即可分享
微信分享提示