无名 发表于 2022-5-8 16:31:07

【梅开三度】java常见实例4

java -classpath 的使用:

java:假设我们的 CLASSPATH 设置为:D:/peng/java/pro ,在该目录下有三个文件:HelloWorld.java / HelloWorldExtendsTestCase / HelloWorldExtendsHelloWorld。这三个文件的类声明分别如下:

HelloWorld.java :public class HelloWorld
HelloWorldExtendsHelloWorld.java :public class HelloWorldExtendsHelloWorld extends HelloWorld
HelloWorldExtendsTestCase.java:public class HelloWorldExtendsTestCase extends junit.framework.TestCase
假设我们已经按照上面关于 javac -classpath 和 javac 绝对路径的使用,顺利地完成了三个文件地编译。现在我们在 C:/Documents and Settings/peng> 目录下执行这三个 .class 文件。

C:/Documents and Settings/peng>javaHelloWorld
Hello World
可以看到执行成功。为什么我们在 C:/Documents and Settings/peng> 执行命令,JVM 能够找到D:/peng/java/pro/HelloWorld.class文件呢?这是因为我们配置了系统变量 CLASSPATH,并且指向了目录:D:/peng/java/pro 。所以 JVM 会默认去该目录下加载类文件,而不需要指定 .class 文件的绝对路径了。

C:/Documents and Settings/peng>java HelloWorldExtendsHelloWorld
Hello World
可以看到执行成功了。HelloWorldExtendsHelloWorld 继承了 HelloWorld 类,所以在执行时JVM会先查找在 CLASSPATH 下是否存在一个HelloWorld.class 文件,因为我们已经成功编译了 HelloWorld 类了,所以可以成功执行 HelloWorldExtendsHelloWorld.class

C:/Documents and Settings/peng>java HelloWorldExtendsTestCase
Exception in thread "main" java.lang.NoClassDefFoundError: junit/framework/TestCase
可以看到程序抛出异常了,提示找不到 junit.framework.TestCase文件。为什么同样在 /peng/java/pro 下,HelloWorldExtendsHelloWorld.class 就可以成功执行,而这个就不行了呢?这是因为:junit.framework.TestCase.class 文件并不存在于当前目录下,所以为了能够让程序成功运行,我们必须通过指定 CLASSPATH 的方式,让 JVM 可以找到 junit.framework.TestCase这个类,如下:

C:/Documents and Settings/peng>java -classpath %CLASSPATH% HelloWorldExtendsTestCase
Hello World
http://cdn.u1.huluxia.com/g4/M00/11/E3/rBAAdmBLv0WADZ2NAAGHcWSt2X4628.jpg
页: [1]
查看完整版本: 【梅开三度】java常见实例4