从类文件中读取一行代码

发布于 2024-12-13 20:27:35 字数 238 浏览 3 评论 0原文

给定一个 StackTraceElement.getLineNumber() ,有没有办法从编译的类文件中读取该行的内容?即使可以匹配该行,类文件的内容是否会被编译器“混淆”?

例如,如果我有:

public void myMethod () {
    MyObj m = new MyObj ();   // can I reconstruct this line as String?
}

Given a StackTraceElement.getLineNumber(), is there a way to read the content of this line from a compiled class file? And even if it is possible to match the line, would the content of the class file will be "obfuscated" by the compiler?

For example if I had:

public void myMethod () {
    MyObj m = new MyObj ();   // can I reconstruct this line as String?
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

擦肩而过的背影 2024-12-20 20:27:35

源代码不包含在编译的类文件中,该类文件包含字节码;所以不,仅从类文件工作,您无法重建该行代码。当然,可以反编译 Java 字节码,并且一个足够完善的反编译器可能会或多或少地重建该代码行,但您必须有一个像样的反编译器。最终结果可能看起来很像也可能不太像原始源代码,具体取决于优化等。

The source code is not contained by the compiled class file, which contains bytecode; so no, working only from the class file you can't reconstruct that line of code. It's possible to de-compile Java bytecode, of course, and a sufficiently well-built decompiler might reconstruct that line of code to a greater or lesser extent, but you'd have to have a decent decompiler. The end results may or may not look much like the original source code, depending on optimisations and such.

绳情 2024-12-20 20:27:35

您可以将源文件包含到您的 war / jar 文件中,您可以将其作为文件读取。字节码仅包含行号,而不包含实际代码

you can include the source file into your war / jar file which you can read as a file. The bytecode only contains the line number not the actual code

苍景流年 2024-12-20 20:27:35

您可以从类文件 (Foo.class) 中检索字节码指令,但不能检索表示源代码的字符串。但是,给定源文件和行号,您可以使用标准文件读取技术从源文件 (Foo.java) 中读取该行。

要了解 .class 文件中包含的信息类型,请查看 javap 工具。我想从技术上讲,您可以对编译到该类的源代码做出最好的猜测,或者对其运行反编译器,但行号不会完全匹配,格式会完全不同,也许最重要的是,不会有注释或使用源保留级别的注释。

You could retrieve the bytecode instructions from the class file (Foo.class), but not the String that represents the source code. However, given a source file and a line number, you could instead read the line from the source file (Foo.java), using standard file reading techniques.

To get an idea of the kind of information contained in a .class file, check out the javap tool. I suppose technically you could make a best guess at the source that compiled to that class, or run a decompiler on it, but line numbers won't match exactly, formatting would be totally different, and perhaps crucially, there would be no comments or annotations using source retention level.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文