使用asm,您可以使用方法visitSource和visitLineNumber在生成的类中创建此调试信息。
编辑:这是一个最小的例子:
import java.io.File;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import java.io.FileOutputStream;
import java.io.IOException;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.CheckClassAdapter;
import static org.objectweb.asm.Opcodes.*;
public class App {
public static void main(String[] args) throws IOException {
ClassWriter cw = new ClassWriter(0);
CheckClassAdapter ca = new CheckClassAdapter(cw);
ca.visit(V1_5, ACC_PUBLIC + ACC_SUPER, "test/Test", null, "java/lang/Object", null);
ca.visitSource("this/file/does/not/exist.txt", null); // Not sure what the second parameter does
MethodVisitor mv = ca.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
mv.visitCode();
Label label = new Label();
mv.visitLabel(label);
mv.visitLineNumber(123, label);
mv.visitTypeInsn(NEW, "java/lang/RuntimeException");
mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "()V");
mv.visitInsn(ATHROW);
mv.visitInsn(RETURN);
mv.visitMaxs(2, 1);
mv.visitEnd();
ca.visitEnd();
File target = new File("target/classes/test/");
target.mkdirs();
FileOutputStream out = new FileOutputStream(new File(target, "Test.class"));
out.write(cw.toByteArray());
out.close();
}
}
运行它会生成一个包含 main 方法的类,该方法抛出 RuntimeException 只是为了查看堆栈跟踪中的行号。首先让我们看看反汇编程序对此有何影响:
$ javap -classpath target/classes/ -c -l test.Test
Compiled from "this.file.does.not.exist.txt"
public class test.Test extends java.lang.Object{
public static void main(java.lang.String[]);
Code:
0: new #9; //class java/lang/RuntimeException
3: dup
4: invokespecial #13; //Method java/lang/RuntimeException."<init>":()V
7: athrow
8: return
LineNumberTable:
line 123: 0
}
所以这个类是从一个不存在的 txt 文件编译的:),LineNumberTable 表示从偏移量 0 开始的字节码对应于这个虚构文件的第 123 行。运行此文件显示此文件和行号也包含在堆栈跟踪中:
$ java -cp target/classes/ test.Test
Exception in thread "main" java.lang.RuntimeException
at test.Test.main(this/file/does/not/exist.txt:123)