从main()方法中获取可执行jar的名称

Eri*_* B. 29 java program-entry-point apache-commons-cli

我创建了一个可执行jar并使用commons-cli为用户提供了在启动客户端时指定命令行参数的能力.一切正常.但是,当我打印jar的用法语句时,我想显示以下内容:

usage: java -jar myprog.jar <options> <file>
--help Display the help message
--debug Enable debugging
....
Run Code Online (Sandbox Code Playgroud)

使用commons-cli可以轻松打印所有选项.然而,"使用"线是头部刮擦.我似乎无法找到从args []获取传递给应用程序的"myprog.jar"名称的方法.

这有什么简单的方法吗?我可以使用一个非常复杂的方法从我的类的类加载器返回跟踪并找出它是否包含在jar中,但这似乎是一个相当难看的答案,应该是一个非常简单的问题.

private String getPath(Class cls) {
    String cn = cls.getName();
    String rn = cn.replace('.', '/') + ".class";
    String path =
            getClass().getClassLoader().getResource(rn).getPath();
    int ix = path.indexOf("!");
    if(ix >= 0) {
        return path.substring(0, ix);
    } else {
        return path;
    }
}
Run Code Online (Sandbox Code Playgroud)

rod*_*ion 48

干得好:

new java.io.File(SomeClassInYourJar.class.getProtectionDomain()
  .getCodeSource()
  .getLocation()
  .getPath())
.getName()
Run Code Online (Sandbox Code Playgroud)

编辑:我看到了你对getSourceCode API的评论.嗯,这可能是你用Java做的最好的.关于getCodeSource()返回null,我认为它主要发生在java.lang.*源位置被"隐藏"的类和其他特殊类中.应该适合你自己的课程.