我现在正试图在几个小时之后想出这个错误,我真的不知道是什么原因造成的。我试图将代码注入类File。 奇怪的是注入适用于ClassWriter.COMPUTE_MAXS,但如果我使用ClassWriter.COMPUTE_FRAMES则抛出ArrayIndexOutOfBoundsException。我需要使用COMPUTE_FRAMES才能运行已编辑的类。我正在使用asm 5.2并且到目前为止只发现COMPUTE_FRAMES的值为2(这可能会对你有所帮助)
我的代码:
InputStream in = new FileInputStream("Paht/To/Class.class");
ClassReader classReader = new ClassReader(in);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES){
@Override
protected String getCommonSuperClass(final String type1, final String type2){
return "java/lang/Object";
}
};
ClassVisitor mcw = new ModifierClassWriter(Opcodes.ASM5, cw);
classReader.accept(mcw, 0);
File outputDir = new File("Path/To/Output/dir");
outputDir.mkdirs();
DataOutputStream dout = new DataOutputStream(new FileOutputStream(new File(outputDir, "NameOfFile.class")));
dout.write(cw.toByteArray());
dout.close();
修饰符方法编写器:
public static class ModifierMethodWriter extends MethodVisitor{
private String methodName;
public ModifierMethodWriter(int api, MethodVisitor mv, String methodName) {
super(api, mv);
this.methodName = methodName;
}
@Override
public void visitCode() {
super.visitCode();
//InjectCodeHere, removed it because it most likely doesnt cause the error
}
}
ModifierClassWriter:
public static class ModifierClassWriter extends ClassVisitor{
private int api;
public ModifierClassWriter(int api, ClassWriter cv) {
super(api, cv);
this.api = api;
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
ModifierMethodWriter mvw = new ModifierMethodWriter(api, mv, name);
return mvw;
}
}
错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at org.objectweb.asm.Frame.a(Unknown Source)
at org.objectweb.asm.Frame.a(Unknown Source)
at org.objectweb.asm.MethodWriter.visitMaxs(Unknown Source)
at org.objectweb.asm.MethodVisitor.visitMaxs(Unknown Source)
at org.objectweb.asm.ClassReader.a(Unknown Source)
at org.objectweb.asm.ClassReader.b(Unknown Source)
at org.objectweb.asm.ClassReader.accept(Unknown Source)
at org.objectweb.asm.ClassReader.accept(Unknown Source)
at package.main.ClassMaker.main(ClassMaker.java:28)
答案 0 :(得分:1)
感谢@ display-name我发现了错误。
super.visitMaxs(4, 2);
“ModifierMethodWriter”中的导致错误,我实际上没有在这里显示的代码。