What is the maximum size of a Java .class file?

前端 未结 3 2037
囚心锁ツ
囚心锁ツ 2020-12-13 09:52

A .class file is a rather well documented format that defines sections and size, and therefore maximum sizes as well.

For instance, a .class

3条回答
  •  抹茶落季
    2020-12-13 10:19

    The theoretical, semi-realistic limit for a class with methods is most likely bound by the constant pool. You can only have 64K across all methods. java.awt.Component has 2863 constants and 83548 bytes. A class which had the same ratio of bytes/constant would run out of constant pool at 1.9 MB. By comparison a class like com.sun.corba.se.impl.logging.ORBUtilSystemException would run out around 3.1 MB.

    For a large class, you are likely to run out of constant in the constant pool around 2 - 3 MB.

    By contract sun.awt.motif.X11GB18030_1$Encoder is full of large constant Strings and it is 122KB with just 68 constants. This class doesn't have any methods.

    For experimentation, my compile blows up with too many constants at around 21800 constants.

    public static void main(String[] args) throws FileNotFoundException {
        try (PrintWriter out = new PrintWriter("src/main/java/Constants.java")) {
            out.println("class Constants {");
            for (int i = 0; i < 21800; i++) {
                StringBuilder sb = new StringBuilder();
                while (sb.length() < 100)
                    sb.append(i).append(" ");
                out.println("private static final String c" + i + " = \"" + sb + "\";");
            }
            out.println("}");
        }
    }
    

    Also it appears that the compiled loads the text into a ByteBuffer. This means the source can't be 1 GB or the compiler gets this error. My guess is that the chars in bytes has overflown to a negative number.

    java.lang.IllegalArgumentException
        at java.nio.ByteBuffer.allocate(ByteBuffer.java:334)
        at com.sun.tools.javac.util.BaseFileManager$ByteBufferCache.get(BaseFileManager.java:325)
    

提交回复
热议问题