简体   繁体   English

Java:自动找到具有main方法的类

[英]java: find a class with main method automatically

Is there a way to tell jvm to look for a class with entry main method automatically rather than to specify it when invoking java ClassWithMainMethod ? 有没有一种方法可以告诉jvm在调用java ClassWithMainMethod时自动使用条目main方法查找类,而不是指定java ClassWithMainMethod

In other words, I have directory with many compiled classes one of which has main method and I want to only specify that directory. 换句话说,我的目录包含许多已编译的类,其中一个具有main方法,我只想指定该目录。

No, there is no way to do that. 不,没有办法做到这一点。 You can create an executable jar, and define what the main class is in the jar manifest, allowing you to use 您可以创建一个可执行jar,并定义jar清单中的主类,从而允许您使用

java -jar MyJar.jar

though. 虽然。

See http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html 参见http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

You may also deliver your app with a script which executes the appropriate command for you: 您还可以使用脚本为您的应用程序提供脚本,该脚本将为您执行适当的命令:

#startup.cmd
java -cp ... com.foo.bar.Main

If, in your scenario: 如果在您的情况下:

  • it is okay to execute the first classfile in a directory; 可以在目录中执行第一个类文件;
  • the classes in this directory are in the default package; 该目录中的类在默认包中;
  • the javap command is available – ie you've got a JDK installed, not just a JRE; javap命令可用–即您已经安装了JDK,而不仅仅是JRE;

you could use the following bash script: 您可以使用以下bash脚本:

#!/usr/bin/env sh
for classfile in *.class; do
    classname=$(echo $classfile | cut -f 1 -d '.')
    echo $classname
    if javap -public $classname | fgrep 'public static void main(java.lang.String[])'; then
        java $classname "$@"
    fi
done

如果您的应用程序位于.jar文件中,则可以在其清单中指定主类

If there are more then one class with main method? 如果有一个以上的main方法类?

I think you can create a executable Jar file and specify class having main function in manifest file. 我认为您可以创建一个可执行的Jar文件,并在清单文件中指定具有主要功能的类。 So, whenever user will run jar file. 因此,无论何时用户将运行jar文件。 Class with main function will be executed. 具有main函数的类将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM