在 Java 平台上偶爾會遇到這類怪事:明明編譯通過,執行時卻跳出「方法不存在」之類的錯誤。若編譯與執行在同一環境,通常不會發生;但一旦「甲環境編譯、乙環境執行」,例如整合環境升級之後,問題就浮現了。根因往往是兩邊的 jar 環境不一致——多了或少了幾個 jar,正是衝突的源頭。
因此,如果能在報錯的位置把該類別所在的路徑或 jar 包路徑印出來,就能定位到真正的 class 檔,確認它是否就是編譯時用到的那一個。
第一種做法是用 ClassPathTest.class.getResource("").getPath(),可以取得該 class 檔的位置,即使它被包在 jar 裡也一樣。但這招並非萬能:某些 jar 加了安全保護,就拿不到路徑。
第二種做法是 LogFactory.class.getProtectionDomain().getCodeSource().getLocation().getFile(),專門用來取得 class 所在 jar 包的路徑,且路徑結構只到 jar 那一層,不含內層包結構。它同樣不是萬能——遇到受安全保護的 jar 一樣無解,例如 java.lang.System 就拿不到任何路徑資訊。
package cn.j2se.junit.classpath;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
public class ClassPathTest {
private static final Log logger = LogFactory.getLog(ClassPathTest.class);
@Test
public void testClassPath() {
String classPath = ClassPathTest.class.getResource("").getPath();
logger.info("the classpath of ClassPathTest is:[" + classPath + "]");
assertEquals(1, 1);
}
@Test
public void testJarPath() throws UnsupportedEncodingException {
// System.class.getResource("") == null
String lfClassPath = LogFactory.class.getResource("").getPath();
logger.info("the classpath of LogFactory is:[" + lfClassPath + "]");
// System.class.getProtectionDomain().getCodeSource() == null
String lfJarPath = LogFactory.class.getProtectionDomain()
.getCodeSource().getLocation().getFile();
logger.info("the jar path of LogFactory is:[" + lfJarPath + "]");
assertEquals(1, 1);
}
}
執行後的輸出:
[INFO ] 2015-08-25 14:26:30 CST
the classpath of ClassPathTest is:[/D:/develop/eclipse_jee_juno_SR2/workspace/lijinlong/j2se/bin/cn/j2se/junit/classpath/]
[INFO ] 2015-08-25 14:26:30 CST
the classpath of LogFactory is:[file:/D:/develop/eclipse_jee_juno_SR2/workspace/lijinlong/j2se/lib/commons-logging-1.1.1.jar!/org/apache/commons/logging/]
[INFO ] 2015-08-25 14:26:30 CST
the jar path of LogFactory is:[/D:/develop/eclipse_jee_juno_SR2/workspace/lijinlong/j2se/lib/commons-logging-1.1.1.jar]
實務上的判讀要點是:如果 getResource("") 印出來的路徑指向原始碼目錄或某個開發機上的 bin 資料夾,執行環境顯然不是你預期的那一個;若指向 jar,再比對 jar 的檔名與版本,通常就能立刻看出是哪個套件被錯誤地打包進來了。