I need to generate new classes (via generation of java byte code) from existing classes. I will analyse the body (expressions) of the methods of a class. The expressions will determine what code I will generate.
For me it is importand to set the source file for the new classes (same as base java file) as well as controlling line numbers (when an exception is thrown the stacktrace should contain line numbers of the base java file).
Example: I have the file BaseClass.java. The compiler generates a BaseClass.class from this. I'd like to analyse this class file and generate the byte codes for a GeneratedClass.class. When at c an exception is thrown the stacktrace should contain "BaseClass.java line 3".
BaseClass.java
1: class BaseClass {
2: void method() {
3: call();
4: }
5:}
GeneratesClaas.class
a: class GeneratedClass {
b: void generatedMethod() {
c: generatedCall();
d: }
e:}
My question: are there libraries that support this requirement? Javassist, ASM or BCEL? What to use for this purpose? Hints how to do it or example code would be especially helpfull.
Edit: Hints what library NOT to use because the requirement can NOT be fullfiled would be helpfull, too :).
With asm, you can use the methods visitSource and visitLineNumber to create this debugging information in the generated class.
Edit: Here is a minimal example:
Running this generates a class containing a main method that throws a RuntimeException just to see the line number in the stack trace. First lets see what a disassembler makes of this:
So this class was compiled from a txt file that does not exist :), the LineNumberTable says that the bytecode starting at offset 0 corresponds to line 123 of this imaginary file. Running this file shows that this file and linenumber is also contained in the stack trace: