I'm trying to understand ASM and am currently stuck at chapter 2.2.4 in the handbook. This should be a simple Java question though.
The example code I'm trying to understand has this line in it called byte[] b1 = ...;
.
Since this is not a complete statement (I even tried it out!) I replaced it with byte[] b1 = new byte[1024];
.
When I compile however I get this weird error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
called three lines later (classReader.accept(classWriter, 0);
). Here's the full code and the full error message:
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
public class ModifyClassExample {
public static void main(String[] args) {
byte[] b1 = new byte[1024];
ClassWriter classWriter = new ClassWriter(0);
ClassReader classReader = new ClassReader(b1);
classReader.accept(classWriter, 0);
byte[] b2 = classWriter.toByteArray();
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at org.objectweb.asm.ClassReader.readStringish(ClassReader.java:3726)
at org.objectweb.asm.ClassReader.readClass(ClassReader.java:3741)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:454)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:424)
at ModifyClassExample.main(ModifyClassExample.java:9)
Process finished with exit code 1
I tried reducing the size of the byte array. That's why I know this error pops up at array lenghts of 14+.
Needless to say I need more than that.
You're not providing any class data in the byte array b1
so it will not work. You can however construct a ClassReader from a standard java class such as
ClassReader classReader = new ClassReader("java.lang.Runnable");.
I'd recommend creating a test class with various constructs and use that as your test subject.
Or use the example in 2.2.3 to generate the data - the last line produces the byte array.