近期我负责的一个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);的结果
可见对象的数据已经根据我们的规则进行了初始化。