被导入的外部类所在源文件通常要打包成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