Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Java Classpath to Load a Class File

Tags:

java

classpath

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?

like image 990
Cerin Avatar asked Jan 25 '10 13:01

Cerin


People also ask

How do I add a class to classpath?

Option 1. Copy jar or zip files to a package's code\jars\static directory. Integration Server adds the files to the classpath when the package loads. Note that if you change the contents of a jar file in a package's code\jars\static directory, you must restart Integration Server for the change to take effect.

What should classpath be set to?

The default value of CLASSPATH is a dot (.). It means the only current directory searched. The default value of CLASSPATH overrides when you set the CLASSPATH variable or using the -classpath command (for short -cp). Put a dot (.)


1 Answers

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
like image 167
Joachim Sauer Avatar answered Nov 09 '22 00:11

Joachim Sauer