Home > Java > javaTutorial > How to use Class Path and Package in Java

How to use Class Path and Package in Java

王林
Release: 2023-05-01 17:01:06
forward
1594 people have browsed it

1. Class path

When you install java with full hope, and then write a hello world excitedly, then compile and run, just waiting for those two beautiful things The word appears in front of me, but unfortunately, I only see Can't find class HelloWorld or Exception in thread "main" java.lang.NoSuchMethodError: maain. Why? The compiled class is obviously there.

Let’s take a look at the running process of the java program. We already know that java is interpreted and run through the java virtual machine, that is, compiled and generated through the java command and javac The .class file is the code to be executed by the virtual machine, called bytecode. The virtual machine loads these bytecodes through the classloader, which is a class in the usual sense. There is a problem here. Where does the classloader know? Where are Java's own class libraries and users' own classes? Or there is a default value (current path). Or there is a user-specified variable to indicate that this variable is the classpath, or parameters are passed to the virtual machine at runtime. These are the three methods of specifying the classpath. The compilation process and the running process are similar, except that one is to find and compile, and the other is to find and load. In fact, the java virtual machine is initialized by java luncher, which is the program java (or java.exe). . The virtual machine searches and loads all required classes in the following order:

  • 1, Boot class: Classes that make up the java platform, including rt.jar and i18n. Classes in jar.

  • 2, Extension classes: Classes that use the java extension mechanism are located in the extension directory ($JAVA_HOME/jre/lib/ext) .jar archive package in.

  • 3, User class: Developer-defined classes or third-party products that do not use the java extension mechanism. You must use the command Use the -classpath option in the line or use the CLASSPATH environment variable to determine the location of these classes. The user's own classes we mentioned above refer specifically to these classes. In this way, generally speaking, users only need to specify the location of user classes to guide Classes and extension classes are "automatically" found.

So what should we do? The user class path is a list of directories containing class files, .jar, .zip files. As for how to find the class specifically, because it involves package issues, which will be discussed below, for the time being it can be considered that as long as the class is included, it is found. This class. The delimiter is slightly different depending on the platform. Unix-like systems are basically ":", windows are mostly ";". The possible source is:

  • 1.".", which is the current directory, this is the default value.

  • 2.CLASSPATH environment variable, once set, the default value will be overwritten.

  • 3. The command line parameter -cp or -classpath, once specified, will overwrite the above two.

  • 4. Specified by the -jar parameter .jar archive, overwrites all other values, and all classes come from this specified archive. Since generating an executable .jar file, some other knowledge is required, such as package, and specific configuration files. , will be mentioned at the end of this article. You can first look at some examples that come with jdk.

Let’s take an example of HelloWorld to illustrate. First make the following assumptions:

  • 1. The current directory is /HelloWorld (or c:\HelloWorld, the former one will be used in the future)

  • 2.jdk version is 1.2.2 (under Linux)

  • 3. The PATH environment variable is set correctly. (This way you can use the tool in any directory)

  • 4. The file is HelloWorld.java, the content is:

 public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!\n");
System.exit(0);
}
}
Copy after login

First of all, this file must be written correctly. If you are familiar with c, it is likely to be written like this:

public static void main(int argc, String[] argv)
{
....
}
Copy after login

This is wrong. If you don’t believe me, you can give it a try. Since there is no Java specification at hand, I make the following guess: A Java application program must start with public static void main(String[]). Anything else that is different will not work.

Up to now, we have only set PATH in terms of settings.

1. The current path means that your .class file is in the current directory,

[HelloWorld]$ javac HelloWorld.java  //这一步不会有多大问题,
[HelloWorld]$ java HelloWorld        // 这一步可能就会有问题.
Copy after login

If there is a problem like the one at the beginning, first make sure that the error is not caused by typing the wrong command. If there is no wrong command, then continue:

[HelloWorld]$ echo $CLASSPATH 或者 c:\HelloWorld>echo %CLASSPATH%
Copy after login

See Check whether the CLASSPATH environment variable is set. If it is set, use the following command:

[HelloWorld]$ CLASSPATH= 或者 c:\HelloWorld> set CLASSPATH=
Copy after login

to make it empty, and then run again. This time the default user class path is ".", So there should not be the same problem. Another way is to add "." to CLASSPATH.

[/]$ CLASSPATH=$CLASSPATH:. 或者 c:\HelloWorld> set CLASSPATH=%CLASSPATH%;.
Copy after login

can also be successful. Good Luck.

2, When your This method can be used if the program requires third-party class library support and is commonly used. For example, commonly used database drivers, servlet packages required for writing servlets, etc. The setting method is to add CLASSPATH to the environment variable. Then you can directly Compiled and run. Let's take HelloWorld as an example. For example, if you want to run it in the root directory, then you can execute it directly in the root directory

 $ java HelloWorld 或者 c:\>java HelloWorld
Copy after login

这样肯定会出错, 如果你的 CLASSPATH 没有改动的话. 我想大家应该知道为什么错了吧, 那么怎么改呢? 前面说过, 用户类路径就是一些包含你所需要的类的目录, .jar 档案包, .zip 包. 现在没有生成包, 所以只好把 HelloWorld.class 所在的目录加到 CLASSPAT了, 根据前面的做法, 再运行一次, 看看, 呵呵, 成功了, 换个路径, 又成功了!! 不仅仅可以直接运行其中的类, 当你要 import 其中的某些类时, 同样处理. 不知道你想到没有, 随着你的系统的不断的扩充, (当然了, 都是一些需要 java 的东西).如果都加到这个环境变量里, 那这个变量会越来越臃肿, 虽然环境变量空间可以开很大, 总觉得有些不舒服. 看看下面一个方法.

3, 在命令行参数中指明 classpath. 还是和上面相同的目标, 在任何目录下执行 HelloWorld, 用这个方法怎么实现呢?

 [/]$ java -cp /HelloWorld HelloWorld 或者 c:\>java -cp c:\HelloWorld HelloWorld
Copy after login

就可以了. 这是这种方法的最简单的应用了. 当你使用了另外的包的时候, 还可以采用用这种方法.

例如:

$ javac -classpath aPath/aPackage.jar:. myJava.java
$ java  -cp aPath/aPackage.jar:. myJava
或者
c:\> javac -classpath aPath\aPackage.jar;. myJava.java
c:\> java  -cp aPath\aPackage.jar;. myJava
Copy after login

这种方法也有一个不方便的的地方就是当第三方包所在的路径较长或者需要两个以上包的时候, 每次编译运行都要写很长, 非常不方便, 这时候可以写脚本来解决.

比如一个例子:

 compile   (文件, 权限改为可执行, 当前目录)
$ cat compile
---------------------------
#!/bin/bash
javac -classpath aPath\aPackage.jar:anotherPath\anotherPackage.jar:. m
yJavva.java
---------------------------
run (文件, 权限改为可执行, 当前目录)
$cat run
---------------------------
#!/bin/bash
java -cp aPath\aPackage.jar:anotherPath\anotherPackage.jar:. myJava
---------------------------
或者:
compile.bat
c:\HelloWorld> type compile.bat
-------------------------
javac -classpath aPath\aPackage.jar:anotherPath\anotherPackage.jar:. m
yJavva.java
-------------------------
run.bat
c:\HelloWorld> type run.bat
------------------------
java -cp aPath\aPackage.jar:anotherPath\anotherPackage.jar:. myJava
------------------------
Copy after login

就可以了. 试试看.

前面提到了扩展类, 扩展类是什么呢? java 的扩展类就是应用程序开发者用来扩展核心平台功能的 java 类的包(或者是 native code). 虚拟机能像使用系统类一样使用这些扩展类. 有人建议可以把包放入扩展目录里, 这样, CLASSPATH 也不用设了,也不用指定了, 岂不是很方便? 确实可以正确运行, 但是个人认为这样不好, 不能什么东西都往里搁, 一些标准的扩展包可以, 比如, JavaServlet, Java3D 等等. 可以提个建议, 加一个环境变量, 比如叫 JARPATH, 指定一个目录, 专门存放用户的 jar zip等包, 这个要等 SUN 公司来做了. windows98 下, 我原来安装的时候, 一直装不上, 总是死机, 好不容易装上了, 缺省的是不能运行正确的, 然后把 tool.jar 放入 CLASSPATH 后工作正常. 现在作测试,去掉仍然是正确的. 经过多次测试, 发现如果原来曾装过 jdk 的都很好, 没有装过的,装的时候会死机, 多装几次就可以了. 如果你发现正确安装后, 不能正常工作, 就把tools.jar 加入 CLASSPATH, 试一下.

二、 包 (package)

Java 中的 "包" 是一个比较重要的概念, package 是这样定义的:Definition: A package is a collection of related classes and interfaces that provides access protection and namespace management. 也就是: 一个包就是一些提供访问保护和命名空间管理的相关类与接口的集合. 使用包的目的就是使类容易查找使用, 防止命名冲突, 以及控制访问. 这里我们不讨论关于包的过多的东西, 只讨论和编译, 运行, 类路径相关的东西.至于包的其他内容, 请自己查阅相关文档. 简单一点来说, 包就是一个目录, 下面的子包就是子目录, 这个包里的类就是这个目录下的文件. 我们用一个例子来说明.

首先建目录结构如下: PackageTest/source/, 以后根目录指的是 PackageTest目录, 我们的源程序放在 source 目录下.

源程序如下:

 PackageTest.java
package pktest;
import pktest.subpk.*;
public class PackageTest
{
private String value;
public PackageTest(String s)
{
value = s;
}
public void printValue()
{
System.out.println("Value of PackageTest is " + value);
}
public static void main(String[] args)
{
PackageTest test = new PackageTest("This is a Test Package");
test.printValue();
PackageSecond second = new PackageSecond("I am in PackageTest");
second.printValue();
PackageSub sub = new PackageSub("I am in PackageTest");
sub.printValue();
System.exit(0);
}
}
PackageSecond.java
package pktest;
public class PackageSecond
{
private String value;
public PackageSecond(String s)
{
value = s;
}
public void printValue()
{
System.out.println("Value of PackageSecond is " + value);
}
}
PackageSub.java
package pktest.subpk;
import pktest.*;
public class PackageSub
{
private String value;
public PackageSub(String s)
{
value = s;
}
public void printValue()
{
PackageSecond second = new PackageSecond("I am in subpackage.");
second.printValue();
System.out.println("Value of PackageSub is " + value);
}
}
Main.java
import pktest.*;
import pktest.subpk.*;
public class Main()
{
public static void main()
{
PackageSecond second = new PackageSecond("I am in Main");
second.printValue();
PackageSub sub = new PackageSub("I am in Main");
sub.printValue();
System.exit(0);
}
}
Copy after login

其中,Main.java是包之外的一个程序,用来测试包外的程序访问包内的类,PackageTest.java属于pktest这个包,也是主程序.PackageSecond.java也属于pktest,PackageSub属于pktest下的subpk包,也就是pktest.subpk.详细使用情况,请参看源程序。

好了, 先把源程序都放在 source 目录下, 使 source 成为当前目录, 然后编译一下, 呵呵, 出错了,Main.java:1: Package pktest not found in import.import pktest.*; 这里涉及到类路径中包是怎么查找的, 前面我们做了一点假设: "只要包含了这个类就算找到了这个类", 现在就有问题了. 其实 jdk 的 工具 javac javajavadoc 都需要查找类, 看见目录, 就认为是包的名字, 对于import 语句来说,一个包对应一个目录. 这个例子中, import pktest.*, 我们知道类路径可以包含一个目录, 那么就以那个目录为根, 比如有个目录 /myclass, 那么就会在查找/myclass/pktest 目录及其下的类. 所有的都找遍, 如果没有就会报错. 由于现在的类路径只有当前目录, 而当前目录下没有 pktest 目录, 所以就会出错. 类路径还可以包含 .jar .zip 文件, 这些就是可以带目录的压缩包, 可以把 .jar .zip文件看做一个虚拟的目录, 然后就和目录一样对待了.

好了, 应该知道怎么做了吧, 修改后的目录结构如下:

 PackageTest
|
|__source   Main.java
|
|__pktest   PackageTest.java   PackageSecond.java
|
|__subpk  PackageSub.java
Copy after login

然后重新编译, 运行, 哈哈, 通过了. 我们再来运行一下 PackageTest.

 [source]$ java pktest/PackageTest
Copy after login

怎么又出错了?

Exception in thread "main" java.lang.NoClassDefFoundError: pktest/PackageTest 是这样的, java 所要运行的是一个类的名字, 它可不管你的类在什么地方, 就象我们前面所讨论的一样来查找这个类, 所以它把 pktest/PackageTest 看成是一个类的名字了, 当然会出错了, 应该这么做,

[source]$ java pktest.PackageTest
Copy after login

大家应该明白道理吧, 我就不多说了. 注意 javac 不一样, 是可以指明源文件路径的, javac 只编译, 不运行, 查找类也只有在源文件中碰到 import 时才会做, 与源文件所在的包没有关系. 似乎还又些不好的地方, 怎么生成的 .class 文件这么分散呀, 看着真别扭. 别急,javac 有一个 -d 命令行参数, 可以指定一个目录, 把生成的 .class 文件按照包给你好好地搁在这个目录里面.

 [source]$ mkdir classes
[source]$ javac -d classes pktest/PackageTest.java
[source]$ javac -d classes Main.java
Copy after login

那么运行怎么运行呢?

[source]$ cd classes
[classes]$ java pktest.PackageTest
[classes]$ java Main
Copy after login

就可以了. 其实 jdk 的这一套工具小巧简单, 功能强大, 不会用或者用错其实不关工具的事, 关键是明白工具背后的一些原理和必要的知识. 集成环境是很好,但是它屏蔽了很多底层的知识, 不出错还好, 一旦出错, 如果没有这些必要的知识就很难办, 只好上 bbs 问, 别人只告诉了你解决的具体方法, 下一次遇到稍微变化一点的问题又不懂了. 所以不要拘泥于工具, java 的这一套工具组合起来使用, 中小型工程(五六十个类), 还是应付得下来的.

三、 jar 文件

以下把 .jar .zip 都看做是 .jar 文件.

1, 从前面我们可以看出来 jar 文件在 java 中非常重要, 极大地方便了用户的使用. 我们也可以做自己的 .jar 包.

还是使用前面那个例子, Main.java 是包之外的东西, 用了 pktest 包中的类,我们现在就是要把 pktest 做成一个 .jar 包, 很简单, 刚才我们已经把 pktest中的 .class 都集中起来了,

就会生成 mypackage.jar 文件, 测试一下, 刚才我们生成的 Main.class 就在classes 目录下, 所以, 从前面可以知道:

[classes]$ java -cp mypackage.jar:. Main
Copy after login

就可以运行了.

2, 如果你看过 jdk 所带的例子, 你就会知道, .jar 还可以直接运行,

 [/demo]$ java -jar aJar.jar
Copy after login

那好, 就那我们的试一试,

看来我们的 jar 和它的 jar 还不一样, 有什么不一样呢? 拿它一个例子出来,重新编译, 生成 .jar 文件, 比较后发现, 是 .jar 压缩包中 META-INF/MANIFEST.MF文件不一样, 多了一行, Main-Class: xxxxx, 再看看出错信息, 原来是没有指定Main-Class, 看看 jar 命令, 发现有一个参数 -m,-m include manifest information from specified manifest file

和出错信息有点关系, 看来它要读一个配制文件. 只好照猫画虎写一个了.

 [classes]$ cat myManifest
Manifest-Version: 1.0
Main-Class: pktest.PackageTest
Created-By: 1.2.2 (Sun Microsystems Inc.)
[classes]$ jar -cvfm mypackage.jar myManifest pktest
added manifest
adding: pktest/(in = 0) (out= 0)(stored 0%)
adding: pktest/PackageSecond.class(in = 659) (out= 395)(deflated 40%)
adding: pktest/subpk/(in = 0) (out= 0)(stored 0%)
adding: pktest/subpk/PackageSub.class(in = 744) (out= 454)(deflated 38%)
adding: pktest/PackageTest.class(in = 1041) (out= 602)(deflated 42%)
[classes]$ java -jar mypackage.jar
Value of PackageTest is This is a Test Package
Value of PackageSecond is I am in PackageTest
Value of PackageSecond is I am in subpackage.
Value of PackageSub is I am in PackageTest
Copy after login

好了, 成功了, 这样就做好了一个可以直接执行的 .jar 文件. 大家可以自己试一试

做一个以 Main 为主程序的可执行的 jar.

下面是一些需要注意的问题:

  • 1, 如果类路径中需要用到 .jar 文件, 必须把 jar 文件的文件名放入类路径, 而不是其所在的目录.

  • 2, 在任何时候, 类名必须带有完全的包名,

  • 3, "." 当前目录最好在你的类路径中.下面是一些常见的编译和运行的模式.

 4. To compile HelloWorld.java app in the default package in C:\MyDir, use
CD \MyDir
C:\jdk1.3\bin\Javac.exe -classpath . HelloWorld.java
5. To run a HelloWorld.class app, in the default package in C:\MyDir, use
CD \MyDir
C:\jdk1.3\bin\Java.exe -classpath . HelloWorld
6. To run a HelloWorld.class app, in the default package in a jar in C:\MyDir, use  CD \MyDir
C:\jdk1.3\bin\Java.exe -classpath HelloWorld.jar HelloWorld
7. To compile a HelloWorld.java app in C:\MyPackage, in package MyPackage, use
CD \
C:\jdk1.3\bin\Javac.exe -classpath . MyPackage\HelloWorld.java
8. To run a HelloWorld.class app in C:\MyPackage, in package MyPackage, use
CD \
C:\jdk1.3\bin\Java.exe -classpath . MyPackage.HelloWorld
9. To run a HelloWorld.class app in C:\MyPackage, in a jar in package MyPackage,, use
CD \MyDir
C:\jdk1.3\bin\Java.exe -classpath HelloWorld.jar MyPackage.HelloWorl
Copy after login

(注: default package 指的是在程序中不指定任何包). 最后一个小小的建议, 把 sun 的 jdk tools documentation 好好地看一看,把 jdk 的那些工具 java javac javadoc jar javap jdb......好好用一用, 会有好处的. The Simplest Is The Best.

The above is the detailed content of How to use Class Path and Package in Java. For more information, please follow other related articles on the PHP Chinese website!

source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template