package com.wc;
import com.wc.domain.Dept;
import com.wc.domain.Emp;
import com.wc.util.RandomUtil;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
/**
* @author nalan
*/
public class App {
public static void main(String[] args) throws Exception {
// String className = "com.wc.domain.Dept";
Object obj = genObj(Dept.class);
Object obj1 = genObj(Emp.class);
System.out.println(obj);
System.out.println(obj1);
}
private static Object genObj(Class<?> clazz) throws Exception {
//根据字节码生成对象
Object obj = clazz.getDeclaredConstructor().newInstance();
//根据字节码获取类中声明的所有方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
//获取方法的名称
String methodName = method.getName();
if (methodName.startsWith("set")) {
//获取方法形参的参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
//如果类型范围是Integer则使用方法调用调用Random-util里面的方法
if (parameterType == Integer.class) {
method.invoke(obj, RandomUtil.genInteger(1000, 9999));
}
if (parameterType == String.class) {
method.invoke(obj, RandomUtil.genString(5, RandomUtil.genInteger(6, 10)));
}
if (parameterType == LocalDate.class) {
method.invoke(obj,RandomUtil.genLocalDate("1999-9-21", "2022-2-22") );
}
if (parameterType == BigDecimal.class) {
//BigDecimal使用时需要新创建一个它的对象然后才能使用
method.invoke(obj, new BigDecimal(Math.random() * 10000 + 1000));
}
}
}
}
return obj;
}
}
根据字节码获取对象和方法
//根据字节码生成对象
Object obj = clazz.getDeclaredConstructor().newInstance();
//根据字节码获取类中声明的所有方法
Method[] methods = clazz.getDeclaredMethods();
通过循环判断来获取方法名称 、参数类型、可以使用random-util调用里面的方法、Bigdecimal使用时需要先创建对象然后再调用赋值
for (Method method : methods) {
//获取方法的名称
String methodName = method.getName();
if (methodName.startsWith("set")) {
//获取方法形参的参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
//如果类型范围是Integer则使用方法调用调用Random-util里面的方法
if (parameterType == Integer.class) {
method.invoke(obj, RandomUtil.genInteger(1000, 9999));
}
if (parameterType == String.class) {
method.invoke(obj, RandomUtil.genString(5, RandomUtil.genInteger(6, 10)));
}
if (parameterType == LocalDate.class) {
method.invoke(obj,RandomUtil.genLocalDate("1999-9-21", "2022-2-22") );
}
if (parameterType == BigDecimal.class) {
//BigDecimal使用时需要新创建一个它的对象然后才能使用
method.invoke(obj, new BigDecimal(Math.random() * 10000 + 1000));
}
}
}
}