Initializing Static Fields in Jasmin

Java allows fields to be initialized inline. For example:

class Cell {

   public static int cellCount = 0;
   private static java.util.Random gen = new java.util.Random();
   private int value = gen.nextInt(100);


   public Cell() {
      cellCount++;
   }
   public int getValue() {
      return value;
   }
}

Inline initialization of fields is a syntactic shortcut. A field can always be initialized in a constructor. But what about static fields? We need to be able to initialize them before any instance of the class is created. To do thgat Java allows classes to declare static blocks that are executed when the class is loaded:

class Cell {

   public static int cellCount;
   private static java.util.Random gen;
   private int value;

   static {
      cellCount = 0;
      gen = new java.util.Random();
   }


   public Cell() {
      value = gen.nextInt(100);
      cellCount++;
   }
   public int getValue() {
      return value;
   }
}

In Jasmin these static blocks translate into a special method called <clinit>, which strands for "class init":

.method static public <clinit>()V
   // init static fields here
   return
.end method

See the following files for a demonstration:

Cell.java

TestCell.java

Cell.j