14 November 2015

what is a static block of code in Java ? (with example of typical usage )


It is so funny ,but more I learn about Java then less I know about Java and sometimes I feel like less I know then better than sleep as more I discover then more I feel ashamed that I didn't know this already.

Today ,for example I discover existence of ... static block code of code.

Static block is a static initializer..It is a block of code that is run when the class is loaded to JVM. It is run after the invocation of the super constructor and before the constructor code is executed. It can be useful for example to setup some data in enum.
More about can be found here: http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7

Example:
package dms.pastor.kb.java.basics.staticblock;

import java.util.HashMap;
import java.util.Map;


/**
* Author Dominik Symonowicz
* Created 14/11/2015
* WWW: http://pastor.ovh.org
* Github: https://github.com/pastorcmentarny
* Google Play: https://play.google.com/store/apps/developer?id=Dominik+Symonowicz
* LinkedIn: uk.linkedin.com/pub/dominik-symonowicz/5a/706/981/
*
*/


public enum TrainStation {
    TIANJIN_RAILWAY_STATION("TJZ"),
    WROCŁAW_GŁÓWNY("We"),
    BATH_STATION("BTH"),
    YORK_STATION("YRK"),
    TOLEDO("TOO"),
    LONDON_SAINT_PANCRAS_INTERNATIONAL("STP"),
    ANTWERP_CENTRAL_STATION("ASS"),
    MILANO_CENTRALE("MIC");

    private final String abbreviation;

    private static final Map lookup = new HashMap<>();

    static {
        for (TrainStation trainStation : TrainStation.values()) {
            lookup.put(trainStation.getAbbreviation(), trainStation);
        }
    }


    TrainStation(final String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static TrainStation get(String abbreviation) {
        return lookup.get(abbreviation);
    }

    public static String getTrainStation(TrainStation trainStation) {
        String name = trainStation.name();
        String stationName = "";
        for(String word : name.split("_")){
           String firstCharacter = word.substring(0, 1);
           String rest = word.substring(1, word.length()).toLowerCase();
           stationName += firstCharacter + rest + " ";
        }
    stationName.substring(0,stationName.length());
    return stationName;
    }

}
Happy weekend everybody !

No comments:

Post a Comment