“实体类”可不可以动态添加“字段”和“属性”
1个回答
展开全部
可以的,你用 javassist, cglib 或者更为底层的工具 ASM 都是可以。
ASM 的话相对复杂一些,参考代码:
下面这个是用 ASM 工具为 Student 类添加一个 public String 类型的 address 属性:
1,需要添加属性的原始类:Student.java
Java code?
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2,添加属性的适配器:AddFieldAdapter.java
Java code?
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
public class AddFieldAdapter extends ClassAdapter {
private int accessModifier;
private String name;
private String desc;
private boolean isFieldPresent;
public AddFieldAdapter(ClassVisitor cv, int accessModifier, String name, String desc) {
super(cv);
this.accessModifier = accessModifier;
this.name = name;
this.desc = desc;
}
ASM 的话相对复杂一些,参考代码:
下面这个是用 ASM 工具为 Student 类添加一个 public String 类型的 address 属性:
1,需要添加属性的原始类:Student.java
Java code?
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2,添加属性的适配器:AddFieldAdapter.java
Java code?
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
public class AddFieldAdapter extends ClassAdapter {
private int accessModifier;
private String name;
private String desc;
private boolean isFieldPresent;
public AddFieldAdapter(ClassVisitor cv, int accessModifier, String name, String desc) {
super(cv);
this.accessModifier = accessModifier;
this.name = name;
this.desc = desc;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询