如何在运行时从java对象获取实例变量的行号 [英] How to get line number of an instance variable from a java object during runtime

查看:30
本文介绍了如何在运行时从java对象获取实例变量的行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时查找 Java 文件中实例变量的行号.到目前为止我的理解,可以通过java反射来完成,但不知道如何去做.

I want to find line number of an instance variable in Java file during run time. So far my understanding, it can be done through java reflection but don't know how to do it.

提前致谢

推荐答案

简短回答:没有做不到.

Short answer: no cannot be done.

如果你想在运行时获得任何类型的行号信息,你首先必须确保你的类已经被编译并保留了行号信息.如果您不拥有这些类文件,则无法保证这一点.

If you want to get any kind of line number information at runtime, you first of all have to be sure that your classes have been compiled retaining line number information. If you do not own those class files, then this is not guaranteed.

其次,不清楚你想要什么:变量声明的行号或变量的初始化,或对变量的另一个赋值.如果是声明(没有赋值),那么无论如何都不会保留行信息(我认为 - 尝试在没有赋值的变量声明上放置调试断点,你就会明白).您可以在带有断点的调试器中观察到的另外两种可能性,但无法以编程方式捕获特定语句.

Secondly, it is not clear what you want: the line number of a variable declaration or the initialization of the variable, or another assignment to the variable. If it were the declaration (without an assignment), then there is not line information retained for that regardless (I think -- try placing a debug breakpoint on a variable declaration that does not have an assignment to it and you will understand). The other two possibilities you could observe in a debugger with breakpoints, but there would be no way to capture a particular statement programatically.

最后,运行时将在堆栈跟踪中显示行号,但显然只有当您强制抛出异常或使用 Thread.currentThread().getStackTrace() 时,这意味着您必须访问和修改您想要测试的每个可能的行号的代码.

Finally, the runtime will show line numbers in stacktraces, but obviously only if you force the throw of an exception or use Thread.currentThread().getStackTrace(), which means you would have to access and modify the code for each possible line number you wanted to test.

我想这可能通过一些自定义注释(使用方面编程)将插入代码以在注释出现的任何地方输出行号,这可能会变得更容易一些,但您仍然必须注释您感兴趣的任何行.

I suppose this might be made a tiny bit easier with some custom annotation that would (using aspect programming) that would insert code to output line numbers wherever the annotation appeared, but you would still have to annotate any line you were interested in.

反射不会给你行号.

这篇关于如何在运行时从java对象获取实例变量的行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆