Setting Java Classpath to Load a Class File

风流意气都作罢 提交于 2019-12-04 09:33:54

问题


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.

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:

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$1.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?


回答1:


When you use "-jar" then only the Class-Path attribute defined in the META-INF/MANIFEST.MF file inside the jar file will influence the classpath.

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

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

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



回答2:


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

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.jar and look at the META-INF/MANIFEST.MF file. 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).

After than change your command line to something like this:

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


来源:https://stackoverflow.com/questions/2132505/setting-java-classpath-to-load-a-class-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!