javac error "code too large"?

I have a unit test where I have statically defined a quite large byte array (over 8000 bytes) as the byte data of a file I don't want to read every time I run my unit test.

private static final byte[] FILE_DATA = new byte[] {
12,-2,123,................
}

This compiles fine within Eclipse, but when compiling via Ant script I get the following error:

[javac] C:\workspace\CCUnitTest\src\UnitTest.java:72: code too large
[javac]     private static final byte[] FILE_DATA = new byte[] {
[javac]                                 ^

Any ideas why and how I can avoid this?


Answer: Shimi's answer did the trick. I moved the byte array out to a separate class and it compiled fine. Thanks!


Asked by: Lyndon136 | Posted: 21-01-2022






Answer 1

Methods in Java are restricted to 64k in the byte code. Static initializations are done in a single method (see link)
You may try to load the array data from a file.

Answered by: Vanessa719 | Posted: 22-02-2022



Answer 2

You can load the byte array from a file in you @BeforeClass static method. This will make sure it's loaded only once for all your unit tests.

Answered by: Aida973 | Posted: 22-02-2022



Answer 3

You can leverage inner classes as each would have it's own 64KB limit. It may not help you with a single large array as the inner class will be subject to the same static initializer limit as your main class. However, you stated that you managed to solve the issue by moving your array to a separate class, so I suspect that you're loading more than just this single array in your main class.

Instead of:

private static final byte[] FILE_DATA = new byte[] {12,-2,123,...,<LARGE>};

Try:

private static final class FILE_DATA
{
    private static final byte[] VALUES = new byte[] {12,-2,123,...,<LARGE>};
}

Then you can access the values as FILE_DATA.VALUES[i] instead of FILE_DATA[i], but you're subject to a 128KB limit instead of just 64KB.

Answered by: Stella932 | Posted: 22-02-2022



Similar questions





Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top