简体   繁体   English

Java类路径(-cp)并将执行传递给该类

[英]Java classpath (-cp) and passing execution to that class

I am relatively new to Java but have a fair understanding about how the class path works with respect to providing a list of folder and jars that make classes available to other classes. 我对Java还是比较陌生,但是对于提供一个使其他类可以使用的类的文件夹和jar列表而言,我对类路径的工作方式有一个很好的了解。

I have compiled a JAR (lets say example.jar) that has a main function where execution normally begins. 我已经编译了一个JAR(例如example.jar),它具有一个通常开始执行的主要功能。 Sometimes I want execution to begin in a different class (lets say myAlternateClass.java), with its own main. 有时,我希望执行从具有自己的main的不同类(例如myAlternateClass.java)开始。 I can achieve this by doing using the -cp argument when executing the jar, for example; 我可以通过在执行jar时使用-cp参数来实现此目的;例如,

java -cp example.jar myAlternateClass

This works as I require but I am unsure of what exactly is happening here. 这可以按我的要求工作,但是我不确定这里到底发生了什么。

I'm not 100% sure on exactly what you're looking for, but I'll give it a shot. 对于所要查找的内容,我不确定100%,但是我会给您一个机会。

There are two ways to use a jar file. 有两种使用jar文件的方法。 If the jar file has a Main-Class specified in its META-INF/MANIFEST.MF file, then you can load java with the jar file and execution will start in the main method of that class. 如果jar文件在其META-INF / MANIFEST.MF文件中指定了Main-Class,则可以使用jar文件加载Java,并且将从该类的main方法开始执行。

java -jar example.jar

On the other hand, a jar file can simply be loaded onto the classpath, which makes all of the classes within it available for use. 另一方面,可以将jar文件简单地加载到类路径中,这样就可以使用其中的所有类。 This is the example you are giving: 这是您提供的示例:

java -cp example.jar org.somewhere.MySecondClass

The -cp example.jar puts all of the classes within the jar on the class path and the second argument org.somewhere.MySecondClass gives the class at which execution should begin. -cp example.jar将所有类放在jar中的类路径中,第二个参数org.somewhere.MySecondClass给出应从其开始执行的类。 This second argument would have to be within the jar since specifying a classpath overrides the default (which is just the current directory). 第二个参数必须在jar中,因为指定类路径将覆盖默认值(仅是当前目录)。 In this case, java ignores any Main-Class specified in the MANIFEST.MF file of the jar (if one even is specified). 在这种情况下,java会忽略jar的MANIFEST.MF文件中指定的任何Main-Class(如果指定了偶数)。

Multiple jar files as well as directories of java files not in a jar can be specified by putting colons between them. 可以通过在多个jar文件之间放置冒号来指定多个jar文件以及不在jar中的java文件目录。 So, 所以,

java -jar example.jar:. MyClass

could launch MyClass from the current directory, but place example.jar on the classpath so that MyClass could create instances of whatever classes are available within example.jar. 可以从当前目录启动MyClass,但是将example.jar放在类路径上,以便MyClass可以创建example.jar中可用的任何类的实例。

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

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