概述
jdk.internal.org.objectweb.asm.ClassWriter
1 要修改的对象
import java.lang.reflect.Field;
public class ClassFile {
private Class clazz;
private String classFilePath;
private String packageName;
public ClassFile(Class clazz, String classFilePath, String packageName) {
this.clazz = clazz;
this.classFilePath = classFilePath;
this.packageName = packageName;
}
public Class getClazz() {
return clazz;
}
public void setClazz(Class clazz) {
this.clazz = clazz;
}
public String getClassFilePath() {
return classFilePath;
}
public void setClassFilePath(String classFilePath) {
this.classFilePath = classFilePath;
}
public String getPackageName() {
return packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
@Override
public String toString() {
return "ClassFile{" +
"clazz=" + clazz +
", classFilePath='" + classFilePath + ''' +
", packageName='" + packageName + ''' +
'}';
}
public static void main(String[] args) {
System.out.println("---------------------------");
Class o = ClassFile.class;
o.getDeclaredFields();
for (Field field : o.getDeclaredFields()) {
System.out.println(field.getName());
}
}
}
2 main方法:
ClassReader classFileR = new ClassReader("com.x.demo.asm.ClassFile");//读取需要增加Field字节码文件 ClassWriter tClassWrite = new ClassWriter(COMPUTE_MAXS);//写入CW AddFieldAdapter addDog2Class = new AddFieldAdapter(tClassWrite, 10, "DOG", "Ljava/lang/String;");//class visitor classFileR.accept(addDog2Class,0);// 拼接转换链 CR->CV->CW byte[] bytes = tClassWrite.toByteArray();//获取转换后的字节码 File classFile = new File("/Users/tz/work/x/src/main/java/com/x/demo/asm/ClassFile.class");//磁盘load到内存文件 FileOutputStream fout = new FileOutputStream(classFile);//输出流对象 fout.write(bytes);//写入磁盘
3 CV class visitor 转换核心代码
import static jdk.internal.org.objectweb.asm.Opcodes.ASM4;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.FieldVisitor;
public class AddFieldAdapter extends ClassVisitor {
private int fAcc;
private String fName;
private String fDesc;
private boolean isFieldPresent;
public AddFieldAdapter(ClassVisitor cv, int fAcc, String fName,
String fDesc) {
super(ASM4, cv);
this.fAcc = fAcc;
this.fName = fName;
this.fDesc = fDesc;
}
@Override
public FieldVisitor visitField(int access, String name, String desc,
String signature, Object value) {
if (name.equals(fName)) {
isFieldPresent = true;
}
return cv.visitField(access, name, desc, signature, value);
}
@Override
public void visitEnd() {
if (!isFieldPresent) {
FieldVisitor fv = cv.visitField(fAcc, fName, fDesc, null, null); //最后增加属性
if (fv != null) {
fv.visitEnd();
}
}
cv.visitEnd();
}
}
4 运行结果
阅读参考:ASM 外文文档
最后
以上就是知性美女为你收集整理的class 文件字节码中增加一个Field 立即举例(String DOG)1 要修改的对象的全部内容,希望文章能够帮你解决class 文件字节码中增加一个Field 立即举例(String DOG)1 要修改的对象所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复