简体   繁体   English

是否应通过“get”方法或公共最终字段或两者来检索Java枚举常量?

[英]Should Java enum constants be retrieved through “get” methods or public final fields or both?

See below code for example: 请参阅以下代码,例如:

public enum Employees {  

    BOB("Bob Barker", "BB", 100);    

    private String fullName; //are these better accessed through public or getFullName() below? 
    private String initials;
    private String age;  

    Employees(String fullName, String initials, int age) {  
        this.fullName = fullName;
        this.initials = initials;
        this.age = age;
    }  

    public String getFullName() {  
        return fullName;
    }  
    //etc ...
}

Which method of accessing more correct or more memory efficient? 哪种方法访问更正确或更高效的内存?

You cannot access the fullName through a static method. 您无法通过static方法访问fullName They are instance fields. 它们是实例字段。

Your code is correct. 你的代码是正确的。 You may wish to mark your String fields as final and rid yourself of the setXXX methods (since Enum values are traditionally immutable). 您可能希望将String字段标记为final并摆脱setXXX方法(因为Enum值传统上是不可变的)。

I would always make enum fields final , which then removes the utility of a setter. 总是将enum字段设为final ,然后删除setter的实用程序。 The enum instance is publicly shared and it is expected to be immutable by most sensible client code. enum实例是公开共享的,并且预期最合理的客户端代码是不可变的。

As far as the getter is concerned, that's up to your personal taste, although convention has it to add a getter and make the field private. 就吸气剂而言,这取决于您的个人品味,尽管惯例是添加吸气剂并使该领域保密。 So your taste has to be "strong". 所以你的品味必须“强大”。

使用getter它的约定......如果你以后使用jstl / el中依赖于使用getters /的bean规范的enum,你就不会得到任何令人讨厌的惊喜。

I think you are misunderstanding the concept of enums. 我认为你误解了枚举的概念。 An enum is a shared instance that does not change. 枚举是一个不会改变的共享实例。 What you describe is a regular mutable Java object. 您描述的是一个常规的可变Java对象。 So the first thing you should do is switch from enum to class : 所以你应该做的第一件事是从enum切换到class

public class Employee {  

    private String fullName;
    private String initials;
    private String age;  

    public Employee(String fullName, String initials, int age) {  
        this.fullName = fullName;
        this.initials = initials;
        this.age = age;
    }  

    public String getFullName() {  
        return fullName;
    }  
    //etc ...
}

Then use your class like a regular class: 然后像普通班一样使用你的班级:

Employee bob = new Employee("Bob Barker", "BB", 100);

Edit 编辑

You have removed your setter now, but still, this still does not look like an enum to me. 你现在已经删除了你的二传手,但是,这对我来说仍然不像一个enum

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

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