我的枚举定义如下
public enum EventBusAddress{
TRADE_PAIR,
ORDER
}
名称方法如下调用
String trade_pair = EventBusAddress.TRADE_PAIR.name();
有人可以解释一下name()方法返回的内容吗?
java.lang.Enum.name()方法返回此枚举常量的名称,与其枚举声明中声明的完全相同。如果没有声明如上所述,它将获取toString()但结果为FINAL。
为什么要用名字? name()是一个final方法,所以它不能被覆盖,所以它比toString更好。
当您使用关键字“enum”时,会通过扩展java.lang.Enum来创建一个类。 java.lang.Enum中的一个方法是'public final String name()'。此方法将枚举的确切声明作为String返回。如果需要,您可以覆盖toString()并获取更具描述性的名称。
来自Java Doc,
/** * 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 */