您的位置:首页 > 编程语言 > Java开发

JAVA classpath, 纠正我一直以来错误的认知

2013-07-24 22:59 211 查看
如何调在CLI中使用java tool(JDK中的java命令)调用一个打包在jar中的类,我想大多数人都能给出笼统的方案:

java -classpath xxxxx com.test.classA

这个答案只能说太笼统,再追问一句,如果这个类还依赖若干jar包,并且这些jar包,包括classA所在的jar包都放在路径/root/lib/ 下,classpath内容应该是什么?

我给我的答案是 -classpath=/root/lib, 这个答案是错误的。

这个错误令我不解,我记忆中classpath只需要指定到文件夹路径就OK了,这是为什么呢?

速查oracle官方文档,好吧,确实纠正了我一直以来的错误观念:

Class paths to the .jar, .zip or .class files. Each classpath should end with a filename or directory depending on what you are setting the class path to:

For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file.
For .class files in an unnamed package, the class path ends with the directory that contains the .class files.
For .class files in a named package, the class path ends with the directory that contains the "root" package (the first package in the full package name)

这是官方文档的说明,什么意思呢:

是说classpath 一般是文件路径或者是文件夹路径,到底是什么跟你classpath的指向有关系:

1. 对于.jar, .zip(.class也可以打zip包,第一次听说) 包来说,classpath应该是指到这些文件上,也就是说classpath是文件路径。

2. 对于没有包路径的class文件来说,classpath指定到该.class文件的父目录就可以了

3. 对有包路径的class文件来说,classpath要指定到包路径最上层(root)的父目录,也就是说有个.,class所在路径是/root/lib/classes/com/test/classA.class其中包路径是com.test.classA, 那么classpath应该是/root/lib/classes才对。

这端描述完整的解释了我之前的错误,对于最初提出的那个问题,正确的应该是classpath=/root/lib/xxx.jar ; xxx.jar; xxx.jar ...

这个问题说明了我没有对JAVA比较底层的知识了解透彻,过于依赖IDE,希望能克服这个毛病。

写的很乱,以备后查。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐