歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java獲取class/jar包路徑

Java獲取class/jar包路徑

日期:2017/3/1 9:25:39   编辑:Linux編程

  在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,我們就無法獲知其路徑信息。

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]

Copyright © Linux教程網 All Rights Reserved