当我们需要测试保存时,自己new对象很麻烦,所以我写了一个通用方法,来自动设置初始值
现在还只能设置String类型,之后再增加设置其他类型。直接上代码。
package com.setValueToObject; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.transaction.NotSupportedException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * TODO * * @author sean * @date 2020/5/13 11:51 AM */ public class ObjectParamOprate<T> { private final static Logger logger = LoggerFactory.getLogger(ObjectParamOprate.class); /** * 只给T对象中的String类型的属性赋值 * @param t * @return * @throws InvocationTargetException * @throws IllegalAccessException * @throws NotSupportedException */ public T setStringVaule(T t) throws InvocationTargetException, IllegalAccessException { Field[] f = t.getClass().getDeclaredFields();; //给test对象赋值 for (int i = 0; i < f.length; i++) { //获取属相名 String attributeName = f[i].getName(); //将属性名的首字母变为大写,为执行set/get方法做准备 String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1); try { //获取Test类当前属性的setXXX方法(私有和公有方法) /*Method setMethod=Test.class.getDeclaredMethod("set"+methodName);*/ //获取Test类当前属性的setXXX方法(只能获取公有方法) Method setMethod = t.getClass().getMethod("set" + methodName, String.class); //执行该set方法 setMethod.invoke(t, attributeName); } catch (NoSuchMethodException e) { logger.warn("不能给[{}]赋值,请自己赋值", attributeName); } } return t; } public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NotSupportedException { Test test = new Test(); ObjectParamOprate<Test> t = new ObjectParamOprate<>(); t.setStringVaule(test); System.out.println(JSON.toJSONString(test)); } }
package com.setValueToObject; import java.math.BigDecimal; public class Test { private String aa; private int bb; private String cc; public String dd; public Test test; public BigDecimal ee; private String ff; public String getFf() { return ff; } public void setFf(String ff) { this.ff = ff; } public String getAa() { return aa; } public void setAa(String aa) { this.aa = aa; } public int getBb() { return bb; } public void setBb(int bb) { this.bb = bb; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public Test getTest() { return test; } public void setTest(Test test) { this.test = test; } public BigDecimal getEe() { return ee; } public void setEe(BigDecimal ee) { this.ee = ee; } }
原文:https://www.cnblogs.com/sean-zeng/p/12881962.html