//1.根据Class.forName找到类
Class<?> clz = Class.forName("com.learn.java.portal.web.TestPojo");
Object object = clz.newInstance();
String name = "";
String type = "";
//2.通过clz.getDeclaredFields()获取类的所有属性,遍历,获取每个属性的名字和类型
for (Field field : clz.getDeclaredFields()) {
//3.因为pojo类字段是private私有属性,所以设置可访问
field.setAccessible(true);
//4.将属性name首字母变成大写,便于构建setXX和getXX方法
name = StringUtils.capitalize(field.getName());
type = field.getGenericType().toString();
if (name.equals("$jacocoData") || type.equals("interface org.slf4j.Logger")) {
continue;
}
//5.构建setXX和getXX方法,clz2为set方法的参数类型
Class<?> clz2 = field.getType();
Method setMethod = clz.getDeclaredMethod("set" + name,clz2);
String getMethodName = "get" + name;
if (type.equals("boolean")) {
getMethodName = "is" + name;
}
Method getMethod = clz.getDeclaredMethod(getMethodName);
//6.执行方法,用get方法给set方法赋值
setMethod.invoke(object, getMethod.invoke(object));