Reputation: 3542
Say I have TryJar.java in ~/jar/
public class TryJar {
public static void hello() {
System.out.println("Hello World!");
}
}
then I type:
javac TryJar.java
jar cf TryJar.jar TryJar.class
I want to import this class in another source file in ~/src/ :
public class TrySrc {
public static void main(String[] args) {
TryJar.hello();
}
}
I tried two ways:
1.
javac -cp ~/jar/TryJar.jar TrySrc.java
it's OK during compilation, but when I try to run it, error occurs:
java -cp .:~/jar/TryJar.jar TrySrc
Exception in thread "main" java.lang.NoClassDefFoundError: TryJar
at TrySrc.main(TrySrc.java:3)
Caused by: java.lang.ClassNotFoundException: TryJar
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 1 more
2.
I try to include in my .bashrc and .profile the following command(I don't have .bash_profile or .bash_login):
export CLASSPATH=$CLASSPATH:~/jar/TryJar.jar
and:
source .bashrc
source .profile
But this time, it's still wrong:
javac TrySrc.java
TrySrc.java:3: error: cannot find symbol
TryJar.hello();
^
symbol: variable TryJar
location: class TrySrc
What should I do to include the external jar file?
EDIT: The total project contains only two directories:
~/jar/:
TryJar.java
TryJar.class
TryJar.jar
~/src/:
TrySrc.java
Jar's structure:
jar tf TryJar.jar
META-INF/
META-INF/MANIFEST.MF
TryJar.class
My system is Ubuntu 12.04, java version:
java version "1.8.0"
Java(TM) SE Runtime Environment (build 1.8.0-b132)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)
Upvotes: 4
Views: 750
Reputation: 1
Its failing at compile time. try to import "TryJar" in TrySrc.java first.
Upvotes: 0
Reputation: 240860
in your way 1:
try changing from
java -cp ~/jar/TryJar.jar TrySrc
to
java -cp .:~/jar/TryJar.jar TrySrc
to include current directory in classpath as well to be able to load TrySrc
Upvotes: 2