我有枚举,看起来像这个例子
public enum Animals {
Cat("Cat", "fluffy animal"),
Dog("Dog", "barking animal");
private String name;
private String description;
}
Animals(String name, String description){
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
Run Code Online (Sandbox Code Playgroud)
从外面的课程我怎样才能获得名称和描述字符串?
您只需为您的字段添加getter:
public enum Animals {
Cat("Cat", "fluffy animal"),
Dog("Dog", "barking animal");
private final String name;
private final String description;
Animals(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用getter访问它们:
Animals.Cat.getName();
Animals.Cat.getDescription();
Run Code Online (Sandbox Code Playgroud)
请注意:请为枚举值使用全大写标识符.使这些领域(name和description)最终成为一个好主意.