引入pom
org.javassist
javassist
3.27.0-GA
Student.class
@Data
public class Student{
@Id
private Long id;
private String studentName;
private Integer age;
}
@Test
public void test1() throws Exception {
Student student = new Student();
student.setStudentName("ltm");
student.setAge(99);
// 需要新增的属性
Map newFieldMap = new HashMap<>();
newFieldMap.put("className", "1班");
ClassPool pool = ClassPool.getDefault();
// 注意: 不能用pool.get(Student.class.getName()),否则报错attempted duplicate class definition for name,原因是同个Class不能在同个ClassLoader中加载两次
CtClass ctClass = pool.get(student.getClass().getName());
// 给class新增属性
for(String fieldName: newFieldMap.keySet()) {