星空网 > 软件开发 > Java

Java获取class/jar包路径

  在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]

 




原标题:Java获取class/jar包路径

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流