方案
为解决类冲突,我们可以使用下述的方案定位一个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]