近期我負責的一個spring boot項目,需要快速規定好api並可以返回模擬數據。項目中我用了swagger。
在編寫api的過程中,我發現java模擬數據太麻煩,特別是屬性多的時候。需要一個一個賦值。
但我發現其實接口返回的數據大多數還是由類來封裝,那么如果能讓封裝數據這些類的對象的數據自己隨機生成,那么將大大減少編碼量,於是有了下面的工具。
工具類的代碼:
package com.sicau.ipig.utils;
import com.sicau.ipig.entity.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Random;
/**
* CommonUtil
* create by chenshihang on 2018/12/30
*/
public class CommonUtil {
/**
* 初始化類數據
* @param cls
* @param <T>
* @return
* @throws Exception
*/
public static <T> T initClassInfo(Class<T> cls) {
T bean=null;
try{
bean = cls.newInstance();
Method[] methods = cls.getDeclaredMethods();
Field[] fields = cls.getDeclaredFields();
for(Field field:fields){
String fieldSetName = parSetName(field.getName());
if (!checkSetMet(methods, fieldSetName)) {
continue;
}
Method fieldSetMet = cls.getMethod(fieldSetName,
field.getType());
fieldSet(bean,fieldSetMet,field);
}
}catch (Exception e){
e.printStackTrace();
System.out.println("initClassInfo調用異常");
}
return bean;
}
/**
* 生成隨機數據
* @param type
* @return
*/
private static Object getRandomInfo(String type) {
try{
if(type.equals("String")){
int length = (int) (Math.random()*10);
String str = "豬豬俠哈哈測試數據拉拉拉老王小王abcdefg1234567890豬大美麗小花冬冬強豆豆新";
char[] chr = str.toCharArray();
Random random = new Random();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < length; i++) {
buffer.append(chr[random.nextInt(46)]);
}
return buffer.toString();
}else if(type.equals("Date")){
return new Date();
}else if(type.equals("Long")){
return (long)(Math.random()*100000);
}else if(type.equals("Integer")){
return (int)(Math.random()*1000);
}else if(type.equals("int")){
return (int)(Math.random()*1000);
}else if(type.equals("Double")){
return Math.random()*100;
}else if(type.equals("Boolean")){
double a = Math.random();
return a>0.5 ;
}
}catch (Exception e){
System.out.println("未找到匹配類型,初始化數據失敗"+type);
}
return "haha";
}
/**
* 拼接在某屬性的 set方法
*
* @param fieldName
* @return String
*/
private static String parSetName(String fieldName) {
if (null == fieldName || "".equals(fieldName)) {
return null;
}
int startIndex = 0;
if (fieldName.charAt(0) == '_')
startIndex = 1;
return "set"
+ fieldName.substring(startIndex, startIndex + 1).toUpperCase()
+ fieldName.substring(startIndex + 1);
}
/**
* 判斷是否存在某屬性的 set方法
*
* @param methods
* @param fieldSetMet
* @return boolean
*/
private static boolean checkSetMet(Method[] methods, String fieldSetMet) {
for (Method met : methods) {
if (fieldSetMet.equals(met.getName())) {
// System.out.println(fieldSetMet+" true");
return true;
}
}
// System.out.println(fieldSetMet+" false");
return false;
}
/**
* 調用某個set方法set數據
* @param bean
* @param fieldSetMet
* @param field
* @throws Exception
*/
private static void fieldSet(Object bean,Method fieldSetMet,Field field) throws Exception{
String fieldType = field.getType().getSimpleName();
Object value = getRandomInfo(fieldType);
if ("String".equals(fieldType)) {
fieldSetMet.invoke(bean, (String)value);
} else if ("Date".equals(fieldType)) {
Date temp = (Date)value;
fieldSetMet.invoke(bean, temp);
} else if ("Integer".equals(fieldType)
|| "int".equals(fieldType)) {
Integer intval = (Integer)value;
fieldSetMet.invoke(bean, intval);
} else if ("Long".equalsIgnoreCase(fieldType)) {
Long temp = (Long)value;
fieldSetMet.invoke(bean, temp);
} else if ("Double".equalsIgnoreCase(fieldType)) {
Double temp = (Double)value;
fieldSetMet.invoke(bean, temp);
} else if ("Boolean".equalsIgnoreCase(fieldType)) {
Boolean temp =(Boolean)value;
fieldSetMet.invoke(bean, temp);
} else {
System.out.println("未找到匹配類型" + fieldType);
}
}
public static void main(String[] args) throws Exception {
Material material =initClassInfo(Material.class);
}
}
用於測試的實體類Material
package com.sicau.ipig.entity;
public class Material {
private Integer id;
private String category;
private String name;
private String productName;
private String manufactureFactory;
private String specification;
private String type;
private String warehouseUnit;
private String useUnit;
private Double unitConversion;
private Integer validDay;
private Integer status;
private String comment;
private Integer farmId;
public Material(Integer id, String category, String name, String productName, String manufactureFactory, String specification, String type, String warehouseUnit, String useUnit, Double unitConversion, Integer validDay, Integer status, String comment, Integer farmId) {
this.id = id;
this.category = category;
this.name = name;
this.productName = productName;
this.manufactureFactory = manufactureFactory;
this.specification = specification;
this.type = type;
this.warehouseUnit = warehouseUnit;
this.useUnit = useUnit;
this.unitConversion = unitConversion;
this.validDay = validDay;
this.status = status;
this.comment = comment;
this.farmId = farmId;
}
public Material() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category == null ? null : category.trim();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName == null ? null : productName.trim();
}
public String getManufactureFactory() {
return manufactureFactory;
}
public void setManufactureFactory(String manufactureFactory) {
this.manufactureFactory = manufactureFactory == null ? null : manufactureFactory.trim();
}
public String getSpecification() {
return specification;
}
public void setSpecification(String specification) {
this.specification = specification == null ? null : specification.trim();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public String getWarehouseUnit() {
return warehouseUnit;
}
public void setWarehouseUnit(String warehouseUnit) {
this.warehouseUnit = warehouseUnit == null ? null : warehouseUnit.trim();
}
public String getUseUnit() {
return useUnit;
}
public void setUseUnit(String useUnit) {
this.useUnit = useUnit == null ? null : useUnit.trim();
}
public Double getUnitConversion() {
return unitConversion;
}
public void setUnitConversion(Double unitConversion) {
this.unitConversion = unitConversion;
}
public Integer getValidDay() {
return validDay;
}
public void setValidDay(Integer validDay) {
this.validDay = validDay;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment == null ? null : comment.trim();
}
public Integer getFarmId() {
return farmId;
}
public void setFarmId(Integer farmId) {
this.farmId = farmId;
}
}
執行Material material =initClassInfo(Material.class);的結果

可見對象的數據已經根據我們的規則進行了初始化。
