如何从枚举中获取字段

Geo*_*hev 0 java enums

我有枚举,看起来像这个例子

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)

从外面的课程我怎样才能获得名称和描述字符串?

ern*_*t_k 6

您只需为您的字段添加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)

请注意:请为枚举值使用全大写标识符.使这些领域(namedescription)最终成为一个好主意.