javac error “code too large”?

喜夏-厌秋 提交于 2019-12-18 14:10:11

问题


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!


回答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.




回答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.




回答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.



来源:https://stackoverflow.com/questions/243097/javac-error-code-too-large

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!