Get name of executable jar from within main() method [duplicate]

*爱你&永不变心* 提交于 2019-12-02 18:00:00

Here you go:

new java.io.File(SomeClassInYourJar.class.getProtectionDomain()
  .getCodeSource()
  .getLocation()
  .getPath())
.getName()

Edit: I saw your comment about getSourceCode API. Well, this is probably the best you can do in Java. About getCodeSource() returning null, I think it mainly happens on classes in java.lang.* and other special classes for which the source location is "hidden". Should work for your own classes though.

Michael Wyraz

You should in any case add a .toURI() before you call getPath(). Thats because of some quirks in java's URL implementation - see how to encode URL to avoid special characters in java for details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!