被導入的外部類所在源文件通常要打包成jar包,java中的jar文件裝的是 .class 文件。它是一種壓縮格式和zip兼容,被稱為jar包。
JDK提供的許多類,也是以jar包的形式提供的。在用的時候呢,你的文件里有很多個類,把這些類和他們的目錄一起壓縮到一個文件中發布出去的。使用者拿到這個jar包之后,只要讓CLASSPATH的設置中包含這個jar文件,java虛擬機在裝載類的時候,就會自動解壓這個jar文件,并將其當成目錄,然后在目錄中查找我們所要的類及類的包名和所對應的目錄的結構。
jar包的打包步驟如下
[root@localhost test]# javac -d . Shoes.java???????????? #編譯
[root@localhost test]# jar -cvf shoejar.jarcom??????????#打包,注意將目錄也要包含進去
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/dangdang/(in = 0) (out= 0)(stored 0%)
adding: com/dangdang/shoe/(in = 0) (out= 0)(stored0%)
adding: com/dangdang/shoe/Shoes.class(in = 771)(out= 466)(deflated 39%)
這樣就得到了一個jar包,我們可以使用unzip解壓驗證一下,如
[root@localhost test]# unzip shoejar.jar
Archive:?shoejar.jar
creating:META-INF/
inflating:META-INF/MANIFEST.MF
creating:com/
creating:com/dangdang/
creating: com/dangdang/shoe/
inflating:com/dangdang/shoe/Shoes.class
可見,jar包中只有類文件。拿到jar包后,該如何使用?
假如jar包存放在如下位置
[root@localhost test]# tree
.
├──Clothes.java
└──jar
└──shoejar.jar
1 directory, 3 files
[root@localhost test]#
首先編譯主類文件,這需要使用-cp或-classpath指定主文件運行所依賴的其他.class文件所在的路徑。我們嘗試編譯Clothes.java文件。如
[root@localhost test]# javac -cp ./jar/* Clothes.java
[root@localhost test]#
編譯成功,運行類文件,但是情況不妙,報找不到Class異常
[root@localhost test]# java?Clothes
i'm making a XL size cloth with color red
Exception in thread "main"java.lang.NoClassDefFoundError: com/dangdang/shoe/Shoe
atClothes.main(Clothes.java:26)
Caused by: java.lang.ClassNotFoundException:com.dangdang.shoe.Shoe
atjava.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
atsun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
atjava.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1more
這是因為jar包中的類文件無法進行加載。
我們再次使用-cp參數指定依賴類路徑,運行
[root@localhost test]# java -cp jar/* Clothes
Error: Could not find or load main class Clothes
[root@localhost test]#
因為cp只指定了依賴類所在的jar目錄,覆蓋了默認的搜索路徑即當前目錄(即.),而當前目錄是Clothes.class文件所在目錄,因此要運行這個.class字節碼文件,需要將當前目錄也加進來(用:隔開),系統才能找到當前目錄下的Java類。
[root@localhost test]# java -cp?.:jar/*?Clothes???????????????#指定搜索路徑
i'm making a XL size cloth with color red
i'm making a pair of shoes with color red and size41
[root@localhost test]# ll
我們也可以使用java本身的類加載功能,即可以把需要加載的jar都扔到JRE_HOME/lib/ext下面,這個目錄下的jar包會在Bootstrap Classloader工作完后由Extension Classloader來加載。
[root@localhost test]# cp jar/shoejar.jar/usr/java/jdk1.8.0_181/jre/lib/ext/
[root@localhost test]# javac Clothes.java?????????????????? #編譯
[root@localhost test]# java Clothes
i'm making a XL size cloth with color red
i'm making a pair of shoes with color red and size41