4

I was wondering whether it is possible to call a static method from a static block in order to initialize static variables. Is e.g. the following possible:

public class AppProperties {

    private static final Logger logger = LoggerFactory.getLogger(AppProperties.class);

    private static final String PARSER_PROPERTIES_FILE = "/parser.properties";
    private static final Properties PARSER_PROPERTIES = new Properties();
    private static final Properties DAO_PROPERTIES = new Properties();

    static {
        loadParserProperties();
        loadDaoProperties();
        // Some other configuration
    }

    public static void loadParserProperties() {
        // Loading parser properties
    }

    //  Further methods omitted

}

Is it good practice?

EDIT: Oracle recommends initialization as follows:

class Whatever {

    public static VarType myVar = initializeClassVariable();

    private static VarType initializeClassVariable() {
        // Initialization code goes here
    }

}

Their explanation is:

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

However, the AppProperties code is also reusable. I have a feeling that I am missing something. Calling static methods from static blocks isn't mentioned, that's why I assume it is bad practice.

aboger
  • 2,214
  • 6
  • 33
  • 47
almeynman
  • 7,088
  • 3
  • 23
  • 37

5 Answers5

0

Static block call your method only once at time of class creation, If you want to call method at time of class creation you can call it.

Static block is only way by which you can call your static methods at time of class creation.

atish shimpi
  • 4,873
  • 2
  • 32
  • 50
0

This should not be any issue related to design or best practice.

Anyways, it is advisable to divide chunk of code/functionality into different functions, and making them static and calling from static block is something your applications demands during loading of class by JVM.

The advantage of static methods is that they can be reused later if you need . So, you kind of get more flexibility with a static method in comparison to the corresponding static initialization block.

for more info here

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

Calling to static method from static block it acceptable in the case of you really want to execute the content in the referred static method only one time when the class is getting initialize in the JVM first time. Further you have to keep it in mind this static block won't ever execute again even though you created multiple object in same type with in your application except the first creation.

However you have to use static variables to store if there any values need to be use with the other object creation cycles.

0

Some extra points about static block might help someone.

Calling static methods inside of static block is accepted only in below conditions.

1) It must contain main method if the java version is 7 or above. Else it will throw below error

Error: Main method not found in class MyClass, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

2) If java version is 6 or below, it will work fine even if we don't have main method.

Example :

// The below code would not work in JDK 1.7 and above
class staticExample { 

    // static block execution without main method in JDK 1.6. 
    static
    { 
        System.out.println("Inside Static Block."); 
        System.exit(0); 
    } 
} 

Output:(In JDK 1.6)

Inside Static Block.

But from JDK 1.7 onwards the above code gives an error in output.

Output:

Error: Main method not found in class staticExample, please define the main method as:
       public static void main(String args[])
       or a JavaFX application class must extend javafx.application.Application
0

You can do this. But it is not the best idea for a couple reasons.

One is that you have hard-wired your class to whatever property files the static method is reading, complicating testing. You can't exercise the class without having the actual files present.

Another is that exception-handling in static blocks is problematic, there's no way to handle an unchecked exception thrown from a static block. See Why doesn't Java allow to throw a checked exception from static initialization block?. You would have to specifically catch everything coming out of the block, and anything that was missed couldn't be caught anywhere in the application.

Dependency injection frameworks will handle injecting this stuff into your classes for you with easier testing and no exception-handling issues.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276