使用ASM为一个类增加属性
使用ASM可以方便的访问和修改一个类,或者在JVM载入前动态更新一个类也是可以的,如下,
- 为一个类动态增加一个属性,类Student如下:
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;
}
}
- 使用ASM实现一个类写入属性AddFieldAdapter,如下:
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;
}
@Override
public FieldVisitor visitField(int access, String name, String desc,
String signature, Object value) {
if (name.equals(this.name)) {
isFieldPresent = true;
}
return cv.visitField(access, name, desc, signature, value);
}
@Override
public void visitEnd() {
if (!isFieldPresent) {
// 若属性不存在则写入
FieldVisitor fv = cv.visitField(accessModifier, name, desc, null, null);
if (fv != null) {
fv.visitEnd();
}
}
cv.visitEnd();
}
}
- 实现一个类AddField调用上面的类去添加属性,如下:
public class AddField {
private Class<?> clazz;
private ClassReader cr;
private ClassWriter cw;
private ClassAdapter ca;
private File classFile;
private final static String CLASS_FILE_SUFFIX = ".class";
public AddField(Class<?> clazz) {
this.clazz = clazz;
}
public void addPublicField(String fieldName, String fieldDesc) {
if(cr == null) {
try {
// com.demo2.Student
cr = new ClassReader(clazz.getCanonicalName());
} catch (IOException e) {
e.printStackTrace();
}
cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
}
if(ca == null) {
ca = new AddFieldAdapter(cw, Opcodes.ACC_PUBLIC, fieldName, fieldDesc);
} else {
ca = new AddFieldAdapter(ca, Opcodes.ACC_PUBLIC, fieldName, fieldDesc);
}
}
public void writeByteCode() {
cr.accept(ca, ClassReader.SKIP_DEBUG);
byte[] bys = cw.toByteArray();
OutputStream os = null;
try {
os = new FileOutputStream(getFile());
os.write(bys);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getFile() {
if(classFile == null) {
StringBuffer sb = new StringBuffer();
sb.append(clazz.getResource("/"))
.append(clazz.getCanonicalName().replace(".", File.separator))
.append(CLASS_FILE_SUFFIX);
classFile = new File(sb.substring(6));
}
return classFile;
}
public static void main(String[] args) {
// 为 Student 添加字段
AddField add = new AddField(Student.class);
// 添加一个名为 address,类型为 java.lang.String 的 public 字段
add.addPublicField("address", "Ljava/lang/String;");
// 再增加一个名为 tel,类型为 int 的 public 方法
add.addPublicField("tel", "I");
// 重新生成 .class 文件
add.writeByteCode();
}
}
使用反编译工具查看生成的CLASS文件,即可看到动态添加的属性了。
————————————————
版权声明:本文为CSDN博主「weistar103」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weistar103/article/details/84396739