package test;
import com.alibaba.fastjson.JSONObject;
import com.inspur.est.mva.uum.generateinfo.data.UumFileTaskDetail;
import com.inspur.est.umc.utils.DateUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* @author: noob
* @description :用來生成實體類的json數據
* @Date : 15:29 2019/06/20
*/
public class 生成測試數據 {
private HashMap parammap = new HashMap();
private Class clazz;
//初始化參數
public 生成測試數據() {
parammap.put(String.class, "test");
parammap.put(Integer.class, DateUtils.getNowSecond());
parammap.put(int.class, DateUtils.getNowSecond());
parammap.put(long.class, DateUtils.getNowSecond());
parammap.put(Long.class, DateUtils.getNowMillis());
parammap.put(Double.class, 123D);
parammap.put(double.class, 123D);
clazz = UumFileTaskDetail.class;
}
@Test
public void test() throws Exception {
test(clazz);
}
public <T> T getValue(Class<T> clazz) {
return (T) parammap.get(clazz);
// String key = clazz.getCanonicalName().substring(clazz.getCanonicalName().lastIndexOf(".") + 1);
}
public <T> T test(Class<T> clazz) throws Exception {
T demo = clazz.newInstance();
Field[] f = clazz.getDeclaredFields();
for (int i = 0; i < f.length; i++) {
//獲取屬相名
String attributeName = f[i].getName();
String type = f[i].getType().getName();
//將屬性名的首字母變爲大寫,爲執行set/get方法做準備
String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
try {
//獲取Test類當前屬性的setXXX方法(私有和公有方法)
Method setMethod = clazz.getMethod("set" + methodName, Class.forName(type));
//獲取Test類當前屬性的setXXX方法(只能獲取公有方法)
//執行該set方法
// setMethod.invoke(demo, getValue(Class.forName(type)));
setMethod.invoke(demo, Class.forName(type).cast(parammap.get(Class.forName(type))));
} catch (NullPointerException nu) {
// System.out.println(MessageFormat.format("本處{0}類型沒有值", type));
System.out.println(String.format("本處%s類型沒有值", type));
} catch (NoSuchMethodException e) {
continue;
}
}
System.out.println(JSONObject.toJSONString(demo));
return demo;
}
}