Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing main arguments from a static initializer

Tags:

java

log4j

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).

like image 760
InterruptedException Avatar asked Jan 26 '15 12:01

InterruptedException


People also ask

When would you use a static initialization block?

A Static Initialization Block in Java is a block that runs before the main( ) method in Java. Java does not care if this block is written after the main( ) method or before the main( ) method, it will be executed before the main method( ) regardless.

When the static initializers are executed?

These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program.

Can I initialize Non static data member inside static block?

Yes... a non-static method can access any static variable without creating an instance of the class because the static variable belongs to the class.


2 Answers

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
like image 116
AlexR Avatar answered Nov 05 '22 12:11

AlexR


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");
    ...
}
like image 32
SMA Avatar answered Nov 05 '22 11:11

SMA