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

前端 未结 7 2026
伪装坚强ぢ
伪装坚强ぢ 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:16

    I'm not clear on the question but I'm going to interpret it as you want to differentiate between the following 2

    java -jar fred.jar

    and

    java package.Main

    Here is an outline line of the program

    import sun.jvmstat.monitor.*;
    ...
    HostIdentifier hostId = new HostIdentifier("localhost");
    MonitoredHost monitoredHost = MonitoredHost.getMonitoredHost(hostId);
    Set jvms = monitoredHost.activeVms();
    for (Object i: jvms) {
       VmIdentifier id = new VmIdentifier("//" + i + "?mode=r");
       MonitoredVm vm = monitoredHost.getMonitoredVm(id, 0);   
       System.out.println(i);
       System.out.println("\t main class: " + MonitoredVmUtil.mainClass(vm, false));
       System.out.println("\t main args: " + MonitoredVmUtil.mainArgs(vm));
       System.out.println("\t jvmArgs: " + MonitoredVmUtil.jvmArgs(vm));
       monitoredHost.detach(vm);
    }
    

    The call MonitoredVmUtil.mainClass(vm, false) will either return 'jar' or the name of your main class eg Main.

    You have to use $JAVA_HOME/lib/tools.jar to compile and run.

提交回复
热议问题