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).
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.
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.
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.
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
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");
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With