I want to have something like MOTIVE { GET_PLAYER, GET_FLAG }
.
And in my object,开发者_如何学运维 I want something like
this.motive = MOTIVE.GET_PLAYER
How can I do this?
You are talking about enum
.
Something like this perhaps?
/**
* Don't use caps for a "class" name :)
*/
public enum Motive {
GET_PLAYER,
GET_FLAG;
}
or (with extra fields):
/**
* Don't use caps for a "class" name :)
*/
public enum Motive {
GET_PLAYER("Assessination Quest"),
GET_FLAG("Capture the Flag PvP");
private Motive(final String desc) {
this.description = desc;
}
public String getDescription() {
return description;
}
private final String description;
}
usage:
public final class MyClass {
private Motive motive;
public MyClass(final Motive motive) {
this.motive = motive;
}
}
Also consider a Motive.UNKNOWN as a default case to which you can initialize fields, so you don't get possible nulls.
And switch statements can switch on enums!
One concern: You cannot compile the enum class, compile the enum-using class, change the enum class (and compile it again) and expect it to work. enums are kind-of inlined at compile time; the compiler is allowed to use in the enum-using class hard-coded "ordinals" of the enums. Always recompile both enum classes and enum-using classes so they stay in sync,
enum examples & doc
精彩评论