当我们需要测试保存时,自己给对象手动设值很麻烦,所以我写了一个通用方法,来自动设置初始值
现在还只能设置String类型,之后再增加设置其他类型。直接上代码。
package com.sf.esg.occp.core;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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
*/
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.substring(0,2));
} catch (NoSuchMethodException e) {
logger.info("不能给[{}]赋值,请自己赋值", attributeName);
}
}
logger.info("{}设值完成:{}", t.getClass().getName(), JSON.toJSONString(t));
return t;
}
}
测试对象:
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; } }