设置 Java 类路径以加载类文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2132505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:56:40  来源:igfitidea点击:

Setting Java Classpath to Load a Class File

javaclasspath

提问by Cerin

I'm new to Java, and I'm unsure how to access a class file located in a specific directory from a separate program jar.

我是 Java 新手,我不确定如何从单独的程序 jar 访问位于特定目录中的类文件。

For example, I have an third party jar file located in /, which is supposed to load MyClass located in /mylib/MyClass.class, so I tried running:

例如,我在 / 中有一个第三方 jar 文件,它应该加载位于 /mylib/MyClass.class 中的 MyClass,所以我尝试运行:

java -jar mainprog.jar -classpath "/mylib" MyClass

but I'm getting the error:

但我收到错误:

Exception in thread "main" java.lang.NoClassDefFoundError: MyClass
Caused by: java.lang.ClassNotFoundException: MyClass
        at java.net.URLClassLoader.run(URLClassLoader.java:221)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:209)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:324)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:269)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:337)

What am I doing wrong?

我究竟做错了什么?

采纳答案by Joachim Sauer

When you use "-jar"then onlythe Class-Pathattribute defined in the META-INF/MANIFEST.MFfile inside the jarfile will influence the classpath.

当您使用"-jar",然后Class-Path中定义的属性META-INF/MANIFEST.MF文件里面jar的文件会影响到类路径。

It will also ignore the MyClassargument (or more specifically: interpret it as an argument to the main-class defined in the MANIFEST.MF).

它还将忽略MyClass参数(或更具体地说:将其解释为 中定义的主类的参数MANIFEST.MF)。

If you simply want to call a class from that jar call it like this:

如果您只是想从该 jar 中调用一个类,请像这样调用它:

java -cp mainprog.jar:/mylib MyClass
// or using this one on windows:
java -cp mainprog.jar;/mylib MyClass

回答by liwp

In your command line you are trying to run MyClassas a program, which based on your description is not what you want.

在您的命令行中,您试图MyClass作为程序运行,根据您的描述,这不是您想要的。

You need to figure out what the main class is that is used to execute the program in the jar. You could unpack the jar file with jar -xf mainprog.jarand look at the META-INF/MANIFEST.MFfile. It should have an entry that indicates that the main class of the jar is (I can't remember the name of the entry right now).

您需要弄清楚用于执行 jar 中程序的主类是什么。您可以解压 jar 文件jar -xf mainprog.jar并查看该META-INF/MANIFEST.MF文件。它应该有一个条目,表明 jar 的主类是(我现在不记得条目的名称)。

After than change your command line to something like this:

之后将您的命令行更改为如下所示:

java -classpath /mainprog.jar:/mylib package.name.to.jar.MainClass