如果您在 jar 中运行 java,您能告诉运行时吗? [英] Can you tell on runtime if you're running java from within a jar?
问题描述
我有一个应用程序,我的一些用户从 Eclipse 运行,而其他用户则使用 jar 文件运行它.
I have an application that some of my users run from Eclipse, and others run it by using a jar file.
我希望在从 jar 中运行时完成一些操作,但我不希望在从 Eclipse 运行时完成它们.
I want some actions to be done when running from within the jar, but I don't want them to be done when running from Eclipse.
有没有办法在运行时知道当前应用程序是否在 jar 中运行?
Is there a way to know on runtime whether the current application is running from within a jar?
谢谢!
迪克拉
推荐答案
好吧,你可以判断一个类是否已经从 JAR 文件加载 - 使用 Foo.class.getResource("Foo.class")
并查看返回的 URL 是否以jar:"开头
Well, you can tell whether or not a class has been loaded from a JAR file - use Foo.class.getResource("Foo.class")
and see whether the returned URL begins with "jar:"
以这个程序为例:
public class Foo {
public static void main(String[] args) {
System.out.println(Foo.class.getResource("Foo.class"));
}
}
运行它从文件系统加载文件:
Running it loading the file from the file system:
file:/C:/Users/Jon/Test/com/whatever/Foo.class
从 jar 文件运行它:
Running it from a jar file:
jar:file:/C:/Users/Jon/Test/foo.jar!/com/whatever/Foo.class
这篇关于如果您在 jar 中运行 java,您能告诉运行时吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!