Enum exeeding the 65535 bytes limit of static initializer… what's best to do?

后端 未结 5 1617
囚心锁ツ
囚心锁ツ 2021-01-03 23:30

I\'ve started a rather large Enum of so called Descriptors that I\'ve wanted to use as a reference list in my model. But now I\'ve come across a compiler/VM

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-03 23:55

    Simple. Don't use enum for this. You can't. It won't work.

    The chances are that your source code does not explicitly refer to many of the enum values. Rather, you are using the enum as a convenient way to map between unique object instances and string names. So just replace the enum type with a type that explicitly manages the mapping, initializing it by reading from a file or database. If you do it right, you will get the computational properties and type-safety of an enum. The only thing you lose is the syntactic sugar ... and the statics.

    This approach will have the added advantage that you can modify the 'descriptors' mapping without modifying the source code of your program.


    By the way, the limitation you are running into is imposed by the JVM class file format. A method or constructor has an upper size limit of 2^16 bytes, and a classes static initialization code is represented as a special method with a funky name.

    UPDATE

    Unfortunately your self-answer solution will still run into a different 64K limit ... if pushed too far. Splitting the initialize() method gets around the method size limit, but there is also a 64K limit on the number of entries in a classes constant pool. Each String literal requires a constant pool entry.

提交回复
热议问题