在Java平臺,偶爾會遇到因為Class的沖突而報錯方法不存在之類的問題,但是編譯的時候又沒有問題。在同一個環境下進行編譯和運行,一般不會出現這種情況;在一個環境下編譯,但是在另一個環境下運行,比如集成環境升級,可能會遇到這種問題。原因可能是集成環境的jar環境和開發環境的不一致,比如多了或少了些jar,正是導致沖突的源頭。 設想如果在報錯的地方,可能獲取該類的路徑或者所在jar包的路徑,就可以定位到這個class文件,并確認是不是我們編譯的時候所用到的class文件。 一般,我們可以用如ClassPathTest.class.getResource("").getPath();的方式獲取ClassPathTest類所對應的class文件的位置,即使它是在一個jar包中;但是使用這種方式對于獲取jar包中的class的路徑,不是萬能的,某些jar包添加了安全保護,就無從獲取了。 我們還可以用LogFactory.class.getPRotectionDomain().getCodeSource().getLocation().getFile();的方式來獲取當前使用的LogFactory的class所在的jar包的路徑,和前一種方式相比,這個是專門用于jar中class的,且路徑結構僅到jar包一層,不包含其內層包結構。但是這個同樣不是萬能的,對于被安全保護的jar,同樣無法獲取。如java.lang.System,我們就無法獲知其路徑信息。測試類:
1 package cn.j2se.junit.classpath; 2 3 import static org.junit.Assert.*; 4 5 import java.io.UnsupportedEncodingException; 6 7 import org.apache.commons.logging.Log; 8 import org.apache.commons.logging.LogFactory; 9 import org.junit.Test;10 11 public class ClassPathTest {12 private static final Log logger = LogFactory.getLog(ClassPathTest.class);13 @Test14 public void testClassPath() {15 String classPath = ClassPathTest.class.getResource("").getPath();16 logger.info("the classpath of ClassPathTest is:[" + classPath + "]");17 18 assertEquals(1, 1);19 }20 21 @Test22 public void testJarPath() throws UnsupportedEncodingException {23 // System.class.getResource("") == null24 String lfClassPath = LogFactory.class.getResource("").getPath();25 logger.info("the classpath of LogFactory is:[" + lfClassPath + "]");26 27 // System.class.getProtectionDomain().getCodeSource() == null28 String lfJarPath = LogFactory.class.getProtectionDomain().getCodeSource().getLocation().getFile();29 logger.info("the jar path of LogFactory is:[" + lfJarPath + "]");30 assertEquals(1, 1);31 }32 }
測試結果:
1 [INFO ] 2015-08-25 14:26:30 CST2 the classpath of ClassPathTest is:[/D:/develop/eclipse_jee_juno_SR2/workspace/lijinlong/j2se/bin/cn/j2se/junit/classpath/]3 4 [INFO ] 2015-08-25 14:26:30 CST5 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/]6 7 [INFO ] 2015-08-25 14:26:30 CST8 the jar path of LogFactory is:[/D:/develop/eclipse_jee_juno_SR2/workspace/lijinlong/j2se/lib/commons-logging-1.1.1.jar]
新聞熱點
疑難解答