简体   繁体   English

从jar文件中,从类中调用main方法,该类从jar外部实现一个类

[英]From a jar file, calling the main method from a class that implements a class from outside the jar

Suppose I have a jar file called 'MyJar.jar' with a class defined like this: 假设我有一个名为“ MyJar.jar”的jar文件,其中的类定义如下:

import SomeInterface;

public class MyClass implements SomeInterface {
   static public void main ( String args[] ) {
     ...
   }
}

Note, however, that the interface 'SomeInterface' is NOT in the jar file. 但是请注意,接口“ SomeInterface”不在jar文件中。 Instead its referenced in another jar file called 'SomeJar.jar' 而是在另一个名为“ SomeJar.jar”的jar文件中引用了它

My manifest-mf file does include something like this: 我的manifest-mf文件确实包含以下内容:

Main-Class: MyClass

Now, assume that I try to run the 'main' method on this 'MyClass' class from my jar file using what seems like workable syntax, ie: 现在,假设我尝试使用似乎可行的语法在jar文件中的“ MyClass”类上运行“ main”方法,即:

java -cp SomeJar.jar -jar MyJar.jar

In this case, I get something like: 在这种情况下,我得到如下信息:

Error: Could not find or load main class MyClass

However, if I rework the syntax like this, everything works fine: 但是,如果我像这样修改语法,一切都会正常工作:

java -cp SomeJar.jar;MyJar.jar MyClass

For a sanity check, I did do the former call with a 'HelloWorld' class with an appropriate manifest file entry and that worked. 为了进行健全性检查,我确实使用了带有适当清单文件条目的'HelloWorld'类进行了前一个调用,并且该调用有效。 It seems that this problem only occurs when the class in question implements an interface that isn't immediately available to the jar file, but instead exists outside of it. 看来,仅当所讨论的类实现的接口无法立即供jar文件使用,而是存在于其外部时,才会出现此问题。 (This might happen for exending a class as well, but I haven't checked) As you can see, I can make things work... just not with the 'java -jar' syntax that I thought would work. (这也可能在扩展类时发生,但是我没有检查)如您所见,我可以使事情工作……只是不使用我认为可以工作的'java -jar'语法。 Additionally, with the former way, I DO NOT get a "NoClassDefFoundError" error (which I thought I would), regardless of whether I include the "-cp" classpath in the "java -jar" call or not. 另外,使用前一种方法,无论是否在“ java -jar”调用中包括“ -cp”类路径,我都不会收到“ NoClassDefFoundError”错误(我以为是)。

Any thoughts why the former "java -jar" call does not work (and does not seem to give any good errors on WHY its not working) and yet the latter "java" call works fine? 有什么想法为什么前一个“ java -jar”调用不起作用(并且似乎没有给出为什么它不起作用的任何很好的错误)而后一个“ java”调用可以正常工作?

The -cp and -jar options both set (rather than append to) the underlying classpath. -cp-jar选项都设置(而不是附加)基础类路径。 Whichever option is on the command-line last will override all former -cp and -jar options. 命令行上的最后一个选项将覆盖所有以前的-cp-jar选项。

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

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