What is the maximum number of methods a Java class can have?
I am thinking to build a VERY large Java class, is there any limit on the number of methods the Java class can have? Can it go into the millions of methods?
upda开发者_StackOverflow社区te: The purpose is, yes, to make a "God" class.
According to the Java class file specification the limit is 65535:
4.10 Limitations of the Java Virtual Machine
The following limitations of the Java virtual machine are implicit in the
class
file format:
- The number of methods that may be declared by a class or interface is limited to 65535 by the size of the
methods_count
item of theClassFile
structure (§4.1). Note that the value of themethods_count
item of theClassFile
structure does not include methods that are inherited from superclasses or superinterfaces.
No. Some relevant pieces from the class file format spec:
The following limitations of the Java virtual machine are implicit in the class file format:
The per-class or per-interface constant pool is limited to 65535 entries by the 16-bit constant_pool_count field of the ClassFile structure (§4.1). This acts as an internal limit on the total complexity of a single class or interface.
The number of methods that may be declared by a class or interface is limited to 65535 by the size of the methods_count item of the ClassFile structure (§4.1). Note that the value of the methods_count item of the ClassFile structure does not include methods that are inherited from superclasses or superinterfaces.
I think this means that you can have 65535 methods, but only if you have no other objects that take up slots in the constant pool (field names for example).
In addition to that, there is also a maximum size for each method:
- The amount of code per non-native, non-abstract method is limited to 65536 bytes by the sizes of the indices in the exception_table of the Code attribute (§4.7.3), in the LineNumberTable attribute (§4.7.8), and in the LocalVariableTable attribute (§4.7.9).
Although methods_count in VM Spec is U2 and hence 65535 the format of a method_info has a name_index and a descriptor_index both of which must point into the constant pool which also has a U2 constant_pool_count so 32767 is the max, even this is of course not possible as it does not allow for any other entries for class name, super class fields etc.
精彩评论