![](/img/trans.png)
[英]Should I name final `Atomic…` member fields as constants (in all uppercase) per Java conventions?
[英]Should Java enum constants be retrieved through “get” methods or public final fields or both?
请参阅以下代码,例如:
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 ...
}
哪种方法访问更正确或更高效的内存?
您无法通过static
方法访问fullName
。 它们是实例字段。
你的代码是正确的。 您可能希望将String字段标记为final
并摆脱setXXX
方法(因为Enum
值传统上是不可变的)。
我总是将enum字段设为final
,然后删除setter的实用程序。 enum
实例是公开共享的,并且预期最合理的客户端代码是不可变的。
就吸气剂而言,这取决于您的个人品味,尽管惯例是添加吸气剂并使该领域保密。 所以你的品味必须“强大”。
使用getter它的约定......如果你以后使用jstl / el中依赖于使用getters /的bean规范的enum,你就不会得到任何令人讨厌的惊喜。
我认为你误解了枚举的概念。 枚举是一个不会改变的共享实例。 您描述的是一个常规的可变Java对象。 所以你应该做的第一件事是从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 ...
}
然后像普通班一样使用你的班级:
Employee bob = new Employee("Bob Barker", "BB", 100);
编辑
你现在已经删除了你的二传手,但是,这对我来说仍然不像一个enum
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.