java获取class所在jar

在类库的开发过程中,有些时候为了self-contain的原因,我们希望所有的资源都打包在jar中,但是有些工具好像无法支持从classpasth直接获取比如velocity的模板合并,此时我们就知道class所在的jar,然后通过jar方式加载velocity资源模板。

String jarFilePath = clazz.class.getProtectionDomain().getCodeSource().getLocation().getFile();  
// URL Decoding  
jarFilePath = java.net.URLDecoder.decode(jarFilePath, "UTF-8"); 
  1. String jarFilePath = clazz.class.getProtectionDomain().getCodeSource().getLocation().getFile();  
  2. // URL Decoding  
  3. jarFilePath = java.net.URLDecoder.decode(jarFilePath, "UTF-8"); 
原文地址:https://www.cnblogs.com/zhjh256/p/5982165.html