JAVA classpath, 糾正我一直以來錯誤的認知

來源:互聯網
上載者:User

如何調在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,希望能克服這個毛病。

寫的很亂,以備後查。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.