如何調在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,希望能克服這個毛病。
寫的很亂,以備後查。