定位所用的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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM