本文介绍了如何定义枚举项目的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了,这也解释了构造函数问题。

This is a pretty good reference on enums that also explains the constructor issues.

枚举是常量,是不可变的。然而,他们可以定义可以具有状态的字段。这是一个可怕的做法,因为开发人员会期望枚举及其关联的值是常量,但是您可以仍然可以在带有getter和setter的枚举中定义非final字段。

Enums are constants and are immutable as such. They can however define fields, that can have state. This is an awful practice, because developers will expect enums and their associated values to be constants, but you can still define a non-final field in an enum with getters and setters.

这是合法的java代码:

This is legal java code:

public enum Color{
    RED("FF0000"),
    GREEN("00FF00"),
    BLUE("0000FF");
    private String code;
    public String getCode(){return code;}
    public void setCode(String code){this.code = code;}
    private Color(String code){this.code = code;}
}

但是它能够像这样的恶意代码:

But it enables evil code like this:

String oldBlue = Color.BLUE.getCode();
Color.BLUE.setCode(Color.RED.getCode());
Color.RED.setCode(oldBlue);

所以在99.99%的情况下:如果你的枚举中有字段,仅提供吸气剂。如果这些字段不是不可变的,请提供防御副本:

So in 99.99 % of cases: if you have fields in your enums, you should make them final and provide getters only. If the fields are not immutable themselves, provide defensive copies:

public enum Band{
    THE_BEATLES("John","Paul","George","Ringo");
    private final List<String> members;
    public List<String> getMembers(){
        // defensive copy, because the original list is mutable
        return new ArrayList<String>(members);
    }
    private Band(String... members){
        this.members=Arrays.asList(members);
    }
}



解决方案



在你的情况下,这很简单:你只需要一个类型为string(immutable)的单个字段,因此在构造函数中初始化它并提供一个getter是完全可以的:

Solution

In your case it's very simple: you just need a single field of type string (immutable), so initializing it in the constructor and providing a getter is perfectly ok:

public enum Checker {

    EMPTY ("Empty"),
    RED ("Red"),
    YELLOW ("Yellow");

    private final String value;

    private Checker(final String value) {
        this.value = value;
    }

    public String getValue() { return value; }
}

这篇关于如何定义枚举项目的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 16:28
查看更多