Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method when class loads in java

I have an action in which I want to use one global kind of variables which will be set with a static values.i.e setting a year hash map like 1-Jan, 2-Feb and so on..

I want to know that is there any mechanism in which this logic will be called only once and then by all the methods, it will be used.

I know about constructor. but still any thing which will be executed once the class is loaded and later on can be used by other methods as and when required.

Thanks in adv...

like image 572
Ved Avatar asked Dec 01 '25 08:12

Ved


1 Answers

Put the initialization code in the static block. Example:

private static Map<Integer, Integer> yourMap;

static {
    yourMap = new HashMap<Integer, Integer>();
    callTheStaticMethod();
}

public static void callTheStaticMethod() {
    ...
}
like image 104
Petar Minchev Avatar answered Dec 03 '25 23:12

Petar Minchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!