简体   繁体   中英

Static block and variables initialization order in java vs groovy

class Test {
      static void main(String... args) {
      StaticExample se = new StaticExample()
      }

}

And in another class as below:

class StaticExample {
    static {
        add();
   }
   
   static int x=90;
    private static void add() {
        System.out.println("-------------"+x);
    }
}

I have a scenario similar to the above.

I understand that in Java, static fields are initialized in the same order they are written. So if the static block is first, I get output as x=0 and if the initialization of x=90 is kept first, I get the output for x as 90. But this is not happening in groovy. Whatever order, I always get x=90. Can someone please clarify this. Also please tell me what should be done if I want the static block to be initialized first in groovy.

Looks like Groovy allows forward referencing of a variable in static block and because of that there is a difference in behavior. If you want to achieve the same by deferring the declaration and initialization of variable. Please refer to my experimental code in Java and Groovy to get an idea.


StaticExample.groovy

class StaticExample {
    static {
        method()
    }

    static int b = a

    static {
        println("Before Initializing a --- a = $a")
    }

    static {
        println("Before Initializing a --- b = $b")
    }

    static int a = 10

    static {
        println("After Initializing a --- a = $a")
    }

    static {
        println("After Initializing a --- b = $b")
    }

    static int x

    static {
        x = 90
        println("Setting x = 90")
    }

    private static void method() {
        println("Inside method $x")
    }
}

StaticExample.java

class StaticExample {
    static {
        method();
    }

    static int b;

    static {
        b = getA();
    }

    private static int getA() {
        return a;
    }

    static {
        System.out.println("Before Initializing a --- a = NOT POSSIBLE");
    }

    static {
        System.out.println("Before Initializing a --- b = " + b);
    }

    static int a = 10;

    static {
        System.out.println("After Initializing a --- a = " + a);
    }

    static {
        System.out.println("After Initializing a --- b = " + b);
    }

    static int x;

    static {
        x = 90;
        System.out.println("Setting x = 90");
    }

    private static void method() {
        System.out.println("Inside method x = " + x);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM