在JAVA基础的学习中学到的枚举类一般是这样的:
enum Weekday {
SUN, MON, TUE, WED, THU, FRI, SAT;
}
而我在实际中碰到的枚举类是这样的:
import lombok.AllArgsConstructor;
@AllArgsConstructor
public enum Test {
SAT("sat"),
SUB("sub");
private String test;
}
public class Test2 {
public static void main(String[] args) {
// 调用
System.out.print(Test.SUB.name());
}
}
一个疑问是在类中声明时的方式:SAT("sat")
,不是传统的public String xxx=xxx
的;另一个疑问是调用的时候name()方法是怎么出来的,为什么能直接输出枚举值。
查看了java Enum源代码:
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {
/**
* The name of this enum constant, as declared in the enum declaration.
* Most programmers should use the {@link #toString} method rather than
* accessing this field.
*/
private final String name;
/**
* Returns the name of this enum constant, exactly as declared in its
* enum declaration.
*
* <b>Most programmers should use the {@link #toString} method in
* preference to this one, as the toString method may return
* a more user-friendly name.</b> This method is designed primarily for
* use in specialized situations where correctness depends on getting the
* exact name, which will not vary from release to release.
*
* @return the name of this enum constant
*/
public final String name() {
return name;
}
}
可以看到name()方法和toString()方法几乎是一样的,可以实现字符串输出。
而枚举类Test首先是一个类,然后是枚举。
Test类中定义的SAT("sat")
是根据Test类的构造方法建立的,因为@AllArgsConstructor注释没有将构造方法显式地定义出来。
实际的构造方法应该是这样的:
Test(String test){}
所以Test中定义的SAT的类型是Test,Test.SAT首先是一个Test实例,然后调用继承Enum中的name()方法。
枚举类更具体的文章可以参考深入理解Java枚举类型(enum)