Search code examples
javaconstructordefaultsuper

Java default constructor without initialization


I have a class similar to the below one with all static methods. Hence the class was not initialized while used in other classes. I have to check a condition before invoking any static methods from this class. Even if i add a default constructor it will not get called. Could someone suggest ideas to have solution without instantiating this class in all of its usages? It need be a default constructor could be a simple other solution.

I need to check everytime the network connectivity before making the call. Static Initializer gets called only first time on load.

        public class ABCServerUtil {

        public static boolean checkServer() {...bla...bla...}


        }

I need some thing like below piece of code to be called and to be exit.

        public ABCServerUtil(){
        if(!isNetworkOnline())
        return;
        }

Solution

  • Use a static Initialization block

    static {
        //whatever code for initialization
    }
    
    • A class can have any number of static initialization blocks
    • they can appear anywhere in the class body
    • static initialization blocks are called in the order that they appear in the source code.

    You should be called every time when method called

    public class Test {
    
        public static void checkServer() {
            if (!checkNetwork()) {
                return;
            }
        }
    
        public static void checkClient() {
            if (!checkNetwork()) {
                return;
            }
        }
    
        private static boolean checkNetwork() {
            return true; // or false depending on network condition
        }
    }