Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to circumvent the size limit of a static initialiser in Java when initialising large amounts of constants

I have a class holding a large a mount of generated constants as such:

public class Constants extends SomeBaseClass {

  // init() is defined in some base class...
  public static final XXX KEY1 = init(...);
  public static final XXX KEY2 = init(...);
  public static final XXX KEY3 = init(...);

  // ...
  public static final XXX KEY2000 = init(...);
}

When the number of generated constants is very high, this results in a static initialiser that is larger than the upper limit for Java method sizes (i.e. > 64kb), resulting in a compiler error. One solution is to create several "block initialisation methods" for blocks that can be guaranteed to produce less than 64kb of byte-code, such that they fit into a method:

public class Constants extends SomeBaseClass {

  public static XXX KEY1;
  public static XXX KEY2;
  public static XXX KEY3;

  // ...
  public static XXX KEY2000;

  static {
    initialise0001To1000();
    initialise1001To2000();
  }

  private static void initialise0001To1000() {
    KEY1 = init(...);
    KEY2 = init(...);
    KEY3 = init(...);
    // ...
  }

  private static void initialise1001To2000() {
    // ...
    KEY2000 = init(...);
  }
}

The drawback of this is that I can no longer declare the constants as final, because they are now no longer initialised directly in the static initialiser.

My question is, how can I circumvent that compiler / JVM limitation in a way that I can still generate static final constants?

like image 271
Lukas Eder Avatar asked May 31 '12 21:05

Lukas Eder


1 Answers

One option would be to use inheritance - have a series of classes Constants1, Constants2, ..., ConstantsN that all define the constants, then have each one inherit from the previous one. The final class Constants can then directly inherit from the last of them. This also lets you mark everything final.

Out of curiosity, how did you end up with a file so large that you couldn't fit the initialization code into the 64KB limit?

Hope this helps!

like image 131
templatetypedef Avatar answered Oct 10 '22 06:10

templatetypedef