手机版
你好,游客 登录 注册
背景:
阅读新闻

Java获取class/jar包路径

[日期:2015-08-28] 来源:Linux社区  作者:ywjy [字体:大 中 小]

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-08/122385.htm

linux
相关资讯       Java获取jar包路径 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款