差異處
這裏顯示兩個版本的差異處。
java:basic:findjarlocation [2017/08/19 23:33] |
java:basic:findjarlocation [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
+ | {{tag>java}} | ||
+ | ====== 找尋某類別的jar檔位置 ====== | ||
+ | ===== Problem ===== | ||
+ | 對於第三方元件,某些情況下並不一定會使用API方式直接呼叫你要的功能,例如目標功能可能會發生非預期的exit、目標功能無法提供在同一JVM下多執行緒執行、無法確保目標功能是否可靠(例如memory leak);如果能允許呼叫外部程式所造成的系統負擔,你可能就會使用外部程式執行的方式去使用你要的功能。 | ||
+ | ===== How to? ===== | ||
+ | 對於目標類別可以透過此方法取得路徑: | ||
+ | <code java> | ||
+ | String scJar = ExampleClass.class.getProtectionDomain().getCodeSource().getLocation().getPath(); | ||
+ | scJar = URLDecoder.decode(scJar, "UTF-8"); | ||
+ | if( PlatformUtil.isWindows() && scJar.startsWith("/") ) { | ||
+ | scJar = scJar.replaceFirst("/", ""); | ||
+ | } | ||
+ | </code> | ||
+ | 另外必須注意Windows上是以/開頭與路徑編碼問題。 | ||
+ | ===== Reference ===== | ||
+ | * [[http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file|How to get the path of a running JAR file?]] |