通过新建实例返回的方式
上代码
package com.xxx.xxx.util;import java.lang.reflect.Field;/*** @auther: zpq* @date: 2020/11/9 14:43* @description: 设置用户信息*/
public class ReflectionUtil {/*** @Description: 通过反射设置字段值* @Exception: IllegalAccessException(表示没有访问权限的异常)* @auther: zpq* @date: 2020/11/9 3:53 下午*/public <T> T setfields(T entity) throws IllegalAccessException {Class<?> clazz = entity.getClass();try {// 获取字段Field deleterid = clazz.getDeclaredField("deleterid");Field deleter = clazz.getDeclaredField("deleter");// 开通权限deleterid.setAccessible(true);deleter.setAccessible(true);// 赋值,不光可以用set 还可以用setInteger等,但是string没提供,用obj就可以deleterid.set(entity, "1");deleter.set(entity, "admin");} catch (NoSuchFieldException e) { // 此异常为 实体内字段不存在e.printStackTrace();}// 返回,强转一下(拿出去之后强转也一样,但是返回值得改成obj类型)return entity;}
}
测试
public class Maintest {public static void main(String[] args) throws IllegalAccessException {WbsData wbsData = new ReflectionUtil().setfields(new WbsData());System.err.println(wbsData.getDeleterid());System.err.println(wbsData.getDeleter());}
}
结果
16:31:34.318 [main] DEBUG org.apache.ibatis.logging.LogFactory - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
1
adminProcess finished with exit code 0
static 修饰的方式
/*** @Description: 通过反射设置用户信息* * @auther: zpq* @date: 2020/11/9 3:53 下午*/public static <T> boolean setfields(T entity) throws IllegalAccessException {Class<?> clazz = entity.getClass();try {// 获取字段deleterid = clazz.getDeclaredField("deleterid");deleter = clazz.getDeclaredField("deleter");// 开通权限deleterid.setAccessible(true);deleter.setAccessible(true);// 赋值deleterid.set(entity, "1");deleter.set(entity, "admin");return true;} catch (NoSuchFieldException e) { // 此异常为 实体内字段不存在e.printStackTrace();}return false;}
批量
/*** @Description: 批量** @auther: zpq* @date: 2020/11/9 4:55 下午*/public static <T> void batchSetFields(Collection<T> entityList) {entityList.forEach(e -> {// 没有配置log 可以直接写:setFields(e) 就可以if (setFields(e)) log.error("批量设置过程中发生错误!");});}
或者
/*** @Description: 批量** @auther: zpq* @date: 2020/11/9 4:55 下午*/public <T> List<T> batchSetFields(List<T> entityList) {List<T> res = new ArrayList<>();entityList.forEach(e -> res.add(setFields(e)));return res;}
本文链接:https://my.lmcjl.com/post/951.html
展开阅读全文
4 评论