简体   繁体   中英

Accessing main arguments from a static initializer

Given:

public class MyClass {

   static {
     // Access to args is needed here
   }

   public static void main(String[] args) {
    ...
   }
}

I'd like to access args in the above mentioned static block.

I'm aware that the static block is executed when the class is loaded (or initialized) and before the static main function, but was still wondering whether it was possible to access its args.

Btw - my end goal is to append to the name of the log file at run-time, before log4j is configured (using system property variable that is derived from one of the arguments that is passed to main).

You cant access arguments of main from static block. Instead (or inaddition) of passing arguments to main, i would suggest you use System parameter like:

java -Dmyvar=value ...

And access it within static block like

static {
    String parameterValue = System.getProperty("myvar");
    ...
}

There is a special system property "sun.java.command" that contains whole command line.

Here is an example:

static {
    System.out.println(System.getProperty("sun.java.command"));
}

When I ran my program with arguments aaa bbb I got the following output:

com.MyClass aaa bbb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM