Is there a way to know if a Java program was started from the command line or from a jar file?

前端 未结 7 2024
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 20:45

I want to either display a message in the console or a pop up, so in case a parameter is not specified, I want to know to which should I display

Something like:

7条回答
  •  终归单人心
    2021-02-03 21:10

    The System.console() trick seems to do the work.

    Here's an alternative: there's a method in the class Class getProtectionDomain() which may be used to know the source of the code the the location from there.

    The funny is, this method is available since 1.2

    I knew I used this before, here's the original answer by erickson

    Here's the proof of concept:

    public class FromJar {
        public static void main( String [] args ) {
            if ( FromJar.class
                     .getProtectionDomain()
                     .getCodeSource()
                     .getLocation()
                     .getFile()
                     .endsWith(".jar") ) {
    
                javax.swing.JOptionPane.showMessageDialog( null, "Launched from Jar" );
    
           } else {
                System.out.println("Launched NOT from Jar :P ");
           }
        }
    }
    

    Here's a short ( 1m aprox ) video to see this code running ( and being written with cat :-o )

提交回复
热议问题