简体   繁体   English

Java类可以具有的最大字段数是多少?

[英]What is the maximum number of fields a Java class can have?

Is there a limit to the number of fields a java class or an associated object instance can have, and if so what is it? Java类或关联的对象实例可以具有的字段数是否有限制,如果是,它是什么?

I am explicitly asking about fields, not methods as was asked in this question: What is the maximum number of methods a Java class can have? 我明确询问的是字段,而不是询问此问题的方法:Java类最多可以有多少个方法?

In the JVM spec it says: 在JVM规范中它说:

The number of fields that may be declared by a class or interface is limited to 65535 by the size of the fields_count item of the ClassFile structure (§4.1) 类或接口可以声明的字段数由ClassFile结构(第4.1节)的fields_count项的大小限制为65535。

The class file format contains a list of field declarations whose size is an unsigned short, hence could allow 65535 declarations, but it is not possible to declare 65535 fields in practice. 类文件格式包含字段声明的列表,该列表的大小为无符号短型,因此可以允许65535个声明,但实际上不可能声明65535个字段。

Each field must have a unique name and type combination and these names and types are stored in the constant pool of the class, which can only hold up to 65534 entries, but will also contain the constants describing the current class and its super class and the attribute names, among other features. 每个字段必须具有唯一的名称和类型组合,并且这些名称和类型存储在该类的常量池中,该常量池最多可容纳65534个条目,但还将包含描述当前类及其超类和常量的常量。属性名称以及其他功能。 Every feature of the class which needs dedicated constant entries will reduce the possible number of declared fields. 该类的每个功能都需要专用的常量条目,这将减少已声明字段的可能数量。

So for Java source code, which requires all fields to have unique names, it is impossible to declare that many fields in a class. 因此,对于要求所有字段都具有唯一名称的Java源代码,不可能在一个类中声明很多字段。 With handcrafted byte code, you may utilize the fact that names do not need to be unique, to declare 65535 fields, but you cannot use all of them within the same class, as accessing the field requires a “name and type” entry describing the unique combination, plus a field descriptor pointing to the “name and type” entry and the declaring class. 使用手工制作的字节码,您可以利用名称不必唯一的事实来声明65535个字段,但是您不能在同一类中使用所有它们,因为访问该字段需要一个“名称和类型”条目来描述唯一的组合,外加指向“名称和类型”条目和声明类的字段描述符。

But keep in mind that classes can inherit fields from the super class. 但是请记住,类可以继承超类的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM