开发者

Is there a Java equivalent to if __FILE__ == $0?

开发者 https://www.devze.com 2023-02-25 06:06 出处:网络
I know that in Python and Ruby there are the snippets if __name__ == \'__main__\': and if __FILE__ == $0, which would run 开发者_StackOverflow中文版only run if the script was opened directly.

I know that in Python and Ruby there are the snippets if __name__ == '__main__': and if __FILE__ == $0, which would run 开发者_StackOverflow中文版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?


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.


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 different main() functions in different files, and compile in only the files that you need.)


Get a stacktrace and have a look at the first method:

Throwable t = new Throwable();
StackTraceElement[] elems = t.getStackTrace();
... elems[elems.length-1] should contain a main method ... check if it is yours :) ...
0

精彩评论

暂无评论...
验证码 换一张
取 消