介绍
根据传入的对象类生成对象,并随机赋值
嗯就是闲的蛋疼
使用方式
1.准备个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserType {
private int aid;// 权限ID
private String aName;//权限名
}
2.使用类
@Test
public void text05() {
Object o = DataUtils.textUtils(Car.class);
System.out.println(o);
}
3.结果
工具方法源码
//测试工具
public static <T> Object textUtils(Class<T> clazz) {
T t = null;
try {
Constructor<T> c = clazz.getConstructor();
t = c.newInstance();
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getWriteMethod = pd.getWriteMethod();
Class<?>[] parameterTypes = getWriteMethod.getParameterTypes();
if (parameterTypes.length == 1) {
String typeName = parameterTypes[0].getSimpleName();
if (typeName.equals("int")) {
getWriteMethod.invoke(t, (int) (Math.random() * 10));
}
if (typeName.equals("float")) {
getWriteMethod.invoke(t, 10.00f);
}
if (typeName.equals("String")) {
getWriteMethod.invoke(t, "text" + (int) (Math.random() * 10));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return t;
}