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

Olivier Grégoire picture Olivier Grégoire · Feb 17, 2017 · Viewed 11.2k times · Source

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

For instance, a .class file contains a magic number (4 bytes), a version (4 bytes), the constant pool (variable size), etc. But sizes can be defined on several levels: you can have 65535 methods and each is limited to 65535 bytes.

What are the other limits? And, if you would make the largest .class file possible, what size would it be?

If needed, limit answers to Java. Meaning that if Scala or Clojure (or...) change some limits, disregard those values.

Answer

Holger picture Holger · Feb 17, 2017

The JVM specification doesn’t mandate a limit for class files and since class files are extensible containers, supporting arbitrary custom attributes, you can even max it out as much as you wish.

Each attribute has a size field of the u4 type, thus, could specify a number of up to 2³²-1 (4GiB). Since, in practice, the JRE API (ClassLoader methods, Instrumentation API and Unsafe) all consistently use either byte[] or ByteBuffer to describe class files, it is impossible to create a runtime class of a class file having more than 2³¹-1 bytes (2GiB).

In other words, even a single custom attribute could have a size that exceeds the size of actually loadable classes. But a class can have 65535 attributes, plus 65535 fields, each of them having 65535 attributes of its own and plus 65535 methods, each of them having up to 65535 attribute as well.

If you do the math, you will come to the conclusion that the theoretical maximum of a still well formed class file may exceed any real storage space (more than 2⁶⁵ bytes).