Can you tell on runtime if you're running java from within a jar?

后端 未结 8 1533
星月不相逢
星月不相逢 2020-12-09 14:54

I have an application that some of my users run from Eclipse, and others run it by using a jar file.

I want some actions to be done when running from within the jar,

8条回答
  •  时光取名叫无心
    2020-12-09 15:17

    You could try:

    boolean inJar = false;
    
    try
    {
      CodeSource cs = DataResolver.class.getProtectionDomain().getCodeSource();
      inJar = cs.getLocation().toURI().getPath().endsWith(".jar");
    }
    catch (URISyntaxException e)
    {
    e.printStackTrace();
    }
    

    If you're running from a jar file then cs.getLocation().toURI() will give you the URI of that file; if you're running from inside Eclipse then it'll probably be the path to directory containing your class files.

提交回复
热议问题