Java 中是否有相当于 if __FILE__ == $0 的函数?
我知道在 Python 和 Ruby 中有这样的片段 if __name__ == '__main__':
和 if __FILE__ == $0
,只有直接打开脚本时才会运行。
这似乎是一个非常有用的功能,我在 Java(我学校的“官方”编程语言)中从未见过。 Java中有类似的东西吗?如果没有,有什么办法可以实现吗?
I know that in Python and Ruby there are the snippets if __name__ == '__main__':
and if __FILE__ == $0
, which would run only run if the script was opened directly.
This seems like a really useful feature that I haven't seen in Java (my school's "official" programming language). Is there any equivalent to this in Java? If not, is there any way to implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
java 有
public static void main(String[] args)
方法。当一个类从命令行作为主类运行时会调用它,并且通常仅在这种情况下调用(您可以直接调用它,但通常没有意义)。所以,在java中,标准是将“主调用”逻辑放在这个方法中。java has the
public static void main(String[] args)
method. this is invoked when a class is run as the main class from the command line, and generally only invoked in such a scenario (you could call it directly, but it usually doesn't make sense). so, in java, the standard is to put "main invocation" logic in this method.要添加到 jthalborn 的答案:
真正的问题不是“我如何在 Java 中做到这一点?”问题是“为什么 Ruby 和 Python 需要这样的拼凑?”
答案是,Ruby 和 Python 期望在加载文件时从头到尾执行文件(无论是作为库还是作为主程序),因此您需要一个 hack 来说“如果我不运行这部分”我被称为图书馆”。 Java 并不期望从头到尾运行一个文件或类。它在特定类中有一个
main()
,其中包含该类用作主程序时的代码。因此,Java 不需要这种 hack。(C 和 C++ 在这方面与 Java 类似,但程序中只能有一个
main()
函数,因此您要么需要使用预处理器来决定编译哪个函数,或者您需要将不同的main()
函数放在不同的文件中,并仅编译您需要的文件。)To add to jthalborn's answer:
The real question isn't "how do I do this in Java?" it's "why do Ruby and Python need such a kludge?"
The answer is that Ruby and Python expect to execute a file from start to finish when the file is loaded (either as a library or as the main program), so you need a hack to say "don't run this part if I'm being called as a library". Java has no expectation of running a file or class from start to finish. It has a
main()
in a particular class which contains code for when that class is being used as the main program. Therefore, Java doesn't need this hack.(C and C++ are like Java in this regard, but you can only have one
main()
function in a program, so you either need to resort to using the preprocessor to decide which one to compile in, or you need to put differentmain()
functions in different files, and compile in only the files that you need.)获取堆栈跟踪并查看第一个方法:
Get a stacktrace and have a look at the first method: