假设我在〜/ jar /中有TryJar.
java
public class TryJar {
public static void hello() {
System.out.println("Hello World!");
}
}
然后我输入:
javac TryJar.java
jar cf TryJar.jar TryJar.class
我想在〜/ src /中的另一个源文件中导入这个类:
public class TrySrc {
public static void main(String[] args) {
TryJar.hello();
}
}
我试过两种方法:
1.
javac -cp ~/jar/TryJar.jar TrySrc.java
在编译期间没问题,但是当我尝试运行它时,会发生错误:
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.
我尝试在我的.bashrc和.profile中包含以下命令(我没有.bash_profile或.bash_login):
export CLASSPATH=$CLASSPATH:~/jar/TryJar.jar
和:
source .bashrc
source .profile
但这一次,它仍然是错误的:
javac TrySrc.java
TrySrc.java:3: error: cannot find symbol
TryJar.hello();
^
symbol: variable TryJar
location: class TrySrc
我该怎么做才能包含外部jar文件?
编辑:
整个项目只包含两个目录:
~/jar/:
TryJar.java
TryJar.class
TryJar.jar
~/src/:
TrySrc.java
Jar的结构:
jar tf TryJar.jar
META-INF/
META-INF/MANIFEST.MF
TryJar.class
我的系统是Ubuntu 12.04,java版本:
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)
最佳答案 在你的方式1:
尝试改变
java -cp ~/jar/TryJar.jar TrySrc
至
java -cp .:~/jar/TryJar.jar TrySrc
在classpath中包含当前目录以便能够加载TrySrc