简体   繁体   English

如何将枚举编写为类?

[英]How to write an enum as a class?

In my project, I manipulate instances of the following class :在我的项目中,我操作以下类的实例:

public class MyClass implements Serializable{

    private MyEnum model;
    
    private Object something; //NOT TRANSIENT
    
    public MyClass(MyEnum model){
        
        this.model = model;
        //something = ...
        
    }
    
}

Every instance of MyClass is created by passing it a model MyClass每个实例都是通过传递一个模型来创建的

public enum MyEnum{
    
    A,
    B,
    C,
    //A lot more of these...
    ;
    
}

I often have to serialize/deserialize instances of MyClass , this is why I marked its field something as NOT transient.我经常要的序列化/反序列化实例MyClass ,这就是为什么我标志着其领域something是不是暂时的。

The behavior is such that :行为是这样的:

  1. During serialization, something and the "identifier" of model will be serialized.在序列化过程中, somethingmodel的“标识符”将被序列化。

  2. During deserialization, something will be deserialized and model will be equal to what it was before, without having to deserialize it since it's an enum.在反序列化期间, something将被反序列化并且model将等于它之前的样子,而不必反序列化它,因为它是一个枚举。

But I have so many of these models that I'm getting for my enum :但是我有很多这样的模型,我为我的 enum 得到了:

"The code for the static initializer is exceeding the 65535 bytes limit" “静态初始化程序的代码超出了 65535 字节的限制”

What is the proper way to fix this problem?解决此问题的正确方法是什么? How to write this enum as a class to work around this limitation?如何将此枚举编写为一个类来解决此限制?

Having such large enum s does not make sense.拥有如此大的enum是没有意义的。 Don't you think that you have too much data in there?你不觉得你那里的数据太多了吗?

You are using enums as a way to map between unique object instances and string names.您正在使用enums作为在唯一对象实例和字符串名称之间进行映射的一种方式。 So replace your enums with another type, for example, String .因此,将您的枚举替换为另一种类型,例如String

TL;DR TL; 博士

You cannot use enum for what you require.您不能使用enum来满足您的需求。 It does not work.这是行不通的。 You could use an ArrayList or array with Strings which is filled through a file or db .您可以使用ArrayList或带有Strings array ,这些Strings通过filedb填充。

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

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