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