定位所用的class

方案

为解决类冲突,我们可以使用下述的方案定位一个class所在的位置

ClassName.class.getResource("").getPath();

获取ClassName所在的位置,即使它是在一个jar包中;如果所在jar包添加了安全保护,会获取失败。

ClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile();

获取ClassName所在jar的位置,如果所在jar被安全保护,则获取失败。

DEMO

 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     @Test
14     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     @Test
22     public void testJarPath() throws UnsupportedEncodingException {
23         // System.class.getResource("") == null
24         String lfClassPath = LogFactory.class.getResource("").getPath();
25         logger.info("the classpath of LogFactory is:[" + lfClassPath + "]");
26         
27         // System.class.getProtectionDomain().getCodeSource() == null
28         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 CST
2         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 CST
5         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 CST
8         the jar path of LogFactory is:[/D:/develop/eclipse_jee_juno_SR2/workspace/lijinlong/j2se/lib/commons-logging-1.1.1.jar]

转载于:https://www.cnblogs.com/ywjy/p/4764087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值