java反射获取父类和子类字段值、赋值


import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.*;

public static void setValueByPropName(String tar, Object o, Object val, Class clazz) { Field field = getFiled(tar, clazz); field.setAccessible(true); ReflectionUtils.setField(field, o, val); } public static Field getFiled(String tar, Class clazz) { String error = null; Field field = null; while (clazz != null) { try { field = clazz.getDeclaredField(tar); error = null; break; } catch (Exception e) { clazz = clazz.getSuperclass(); error = e.getMessage(); } } if (error != null || field == null) { throw new RuntimeException("无法获取源字段:" + tar); } return field; } public static Object getValueByPropName(String filedName, Object o, Class clazz) { Field field = getFiled(filedName, clazz); field.setAccessible(true); return ReflectionUtils.getField(field, o); }

 

调用方式:

// 获取id的值
Object var = getValueByPropName("id", a, clazz);

// 赋值name -> lisi
setValueByPropName("name", a, "lisi", clazz);


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM