Static block executing after entering main method

511 views Asked by At

I have a class where i have my main method from where i am calling two static getter calls of singleton pattern. That is, i have 2 classes which have static blocks and have getters for each of them. The following is for reference.

public class RestAPIMain {


public static void main(String[] args) throws MalformedURLException, IOException, SAXException, XMLStreamException {
    System.out.println("Starting main");

    LinkedHashMap<String, String> urlresponses = URLResponse.getURLResponselist();
    LinkedList<String> xmllist = XMLLoad.getXMLFiles();
    System.out.println(xmllist);

The above code has getURLResponselist and getXMLFiles whose classes load the XML file and Properties file using static block and then use the List/Map to store and retrieve values using getter as follows:

FILELOADING:

public class FileLoad {

public static Map<String, Object> jsonload;
public static Map<String, Object> executioncontrol;

static {
    System.out.println("loading static for fileload");
    URL path = FileLoad.class.getResource("FileLoad.class");

    try {
        Enumeration<URL> e = ClassLoader.getSystemResources("/resources/json/");
        while (e.hasMoreElements()) {
            URL u = e.nextElement();
            String fileName = u.getFile();
            File folder = new File(fileName);
            File[] listOfFiles = folder.listFiles();
            for (File file : listOfFiles) {
                InputStream fis = new FileInputStream(file);
                if (file.getName().equals("RestURLS.json")) {
                    jsonload = CommonUtil.jsonToMap(IOUtils.toString(fis, "UTF-8"));
                } else if (file.getName().equals("RestExecution.json")) {
                    executioncontrol = CommonUtil.jsonToMap(IOUtils.toString(fis, "UTF-8"));
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

public static Map<String, Object> getJSONFiles() {
    return jsonload;
}

public static Map<String, Object> getRestExecution() {
    return executioncontrol;
}

PROPERTIESLOAD

public class PropertiesLoad {

private static Properties prop = new Properties();
public static LinkedHashMap<String, String> allkeyvalues = new LinkedHashMap<String, String>();

static {
    System.out.println("loading static for properties");
    InputStream ins;

    try {
        ins = new PropertiesLoad().getClass().getResourceAsStream("/resources/Rest.properties");
        prop.load(ins);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static String getPropValue(String key) {
    String propkey = prop.getProperty(key);
    return propkey;
}

public static LinkedHashMap<String, String> getAllKeysValues() {
    String value = null;
    String key = null;
    for (Entry<Object, Object> keyvalues : prop.entrySet()) {
        key = (String) keyvalues.getKey();
        value = (String) keyvalues.getValue();
        allkeyvalues.put(key, value);
    }
    return allkeyvalues;
}

}

URLResponse

public class URLResponse {

public static LinkedHashMap<String, String> urlresponses = new LinkedHashMap<String, String>();

@SuppressWarnings("unused")
public static LinkedHashMap<String, String> getURLResponselist() throws MalformedURLException, IOException {

    LinkedHashMap<String, String> allkeyvalues = PropertiesLoad.getAllKeysValues();

    for (String urlkey : allkeyvalues.keySet()) {

        String urls = allkeyvalues.get(urlkey);
        System.out.println(urls);
        URL url = new URL(urls);
        InputStream urlins = new URL(urls).openStream();
        if (!(urlins.read() == -1)) {
            String xmlresponse = IOUtils.toString(urlins, "UTF-8");
            urlins.close();
            urlresponses.put(urlkey, xmlresponse);
        } else {
            HttpURLConnection http = (HttpURLConnection) ((URL) url).openConnection();
            int statusCode = http.getResponseCode();
            // TODO:add log
        }
    }
    // TODO:add log
    return urlresponses;
}

}

The URLResponse calls up the getmethod from Propertiesload which loads the properties file through static block and file load also has static block which is then used by main method to get the files loaded.

The observation here is the static block is execution after the main method call when the call goes to the getter method and not before main method starts execution.Added print statements in static blocks also show that the control first goes to main method and from their then moves to static block and static block executes.

My requriment is to load the XML files and the Properties files and other files before main method during class loading and use just getters to retrieve the collections in which we are storing it,like singleton. Also, i read that class is first - loaded, then linked and then initialized. So, static blocks executes during loading, but not happening so in my case.

Kindly guide me as to where my approach is wrong and how it is happening so in my code that static block is executing after main method call.

1

There are 1 answers

4
Ravindra Ranwala On BEST ANSWER

Well, In Java static block gets executed at class loading time. In your case remove all the static blocks that you currently have and place them inside your methods. Then in your main class create a static block and do the necessary invocations which needs to be completed before the main method starts. An example code is given below.

package com.demo;

public class Sample {
    public static void print(String msg){
        System.out.println(msg);
    }

}


package com.demo;

public class Test {

    static{
        Sample.print("Invokes Before Main ...");
    }
    public static void main(String[] args) {
        System.out.println("Inside Main ....");

    }

}

Hope this helps. Happy Coding.