国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Java獲取class/jar包路徑

2019-11-15 01:17:14
字體:
來源:轉載
供稿:網友
java獲取class/jar包路徑 Posted on 2015-08-27 18:02 一尾金魚 閱讀(...) 評論(...) 編輯 收藏

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临江市| 普陀区| 两当县| 长汀县| 韶关市| 永福县| 新邵县| 康定县| 丹江口市| 霍城县| 乐陵市| 清河县| 凭祥市| 崇礼县| 青冈县| 松溪县| 衡南县| 和平区| 卢龙县| 阜阳市| 鄯善县| 如东县| 桐庐县| 仪陇县| 棋牌| 勐海县| 湖南省| 青铜峡市| 金坛市| 奉贤区| 丹棱县| 体育| 朝阳市| 荔波县| 康乐县| 长顺县| 五常市| 库车县| 余江县| 新源县| 印江|