从main()方法中获取可执行jar的名称 [英] Get name of executable jar from within main() method

查看:88
本文介绍了从main()方法中获取可执行jar的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created an executable jar and using commons-cli to give the user the ability to specify command line parameters when he launches the client. Everything works fine. However, when I print the usage statement for the jar, I would like to show the following:

usage: java -jar myprog.jar <options> <file>
--help Display the help message
--debug Enable debugging
....

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

Printing of all the options is easily done with commons-cli. However, the "usage" line is the head scratcher. I cannot seem to figure out a way to get the "myprog.jar" name from the args[] that are passed to the application.

有没有简单的方法可以做到这一点?我可以使用一个复杂的方法从类的类加载器中返回跟踪信息,并弄清它是否包含在jar中,但是对于应该是一个非常简单的问题来说,这似乎是一个相当丑陋的答案.

Is there any easy way of doing this? I could use a pretty convoluted method to back trace from my class' classloader and figure out if it is contained within a jar, but that seems like a fairly ugly answer to what should be a pretty simple question.

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;
    }
}

推荐答案

在这里:

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

编辑:我看到了您对getSourceCode API的评论.好吧,这可能是用Java可以做到的最好的事情.关于getCodeSource()返回null的问题,我认为它主要发生在java.lang.*中的类和其他源"隐藏在其上的特殊类中.不过应该适合您自己的班级.

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.

这篇关于从main()方法中获取可执行jar的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆