Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-10721

Unexpected static initialization order

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Open
    • Minor
    • Resolution: Unresolved
    • 3.0.8, 4.0.4
    • None
    • None
    • None
    • openjdk 11.0.12 2021-07-20

    Description

      Hi, I've encountered a small issue - assignments to static fields and executions of static blocks do not happen in the same order they do in Java. I'm not sure if they should, hence the ticket. In Java the assignments and executions are in the declaration order, while Groovy seems to initialize fields first. Attached sample java class, executable in groovy too. 

      import java.util.*;
      
      class ListSupplier{
          public static List getList(){
              System.out.println("Getting list");
              return new ArrayList<>();
          }
      }
      
      class ListThenStatic{
          static final List list = ListSupplier.getList();
          static{
              System.out.println("Static block");
          }
      }
      
      class StaticThenList{
          static{
              System.out.println("Static block");
          }
          static final List list = ListSupplier.getList();
      }
      
      class Test {
          public static void main(String[] args) {
              ListThenStatic listThenStatic = new ListThenStatic();
              StaticThenList staticThenList = new StaticThenList();
          }
      }

      Java produces output:

      1. Getting list
      2. Static block
      3. Static block
      4. Getting list

      From Groovy:

      1. Getting list
      2. Static block
      3. Getting list
      4. Static block

      Is this behaviour expected and/or documented anywhere?

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              nluk Luk N
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated: