簡體   English   中英

在給定的Java代碼中,將返回什么name()方法?

[英]In the given Java code, what name() method will return?

我的枚舉定義如下

public enum EventBusAddress{
   TRADE_PAIR,
   ORDER 
}

和名稱方法如下

String trade_pair = EventBusAddress.TRADE_PAIR.name();

有人可以解釋一下返回的name()方法嗎?

java.lang.Enum.name()方法返回此枚舉常量的名稱,該名稱與在其枚舉聲明中聲明的完全相同。 如果未如上聲明,它將使您到達toString(),但結果為FINAL。

為什么使用名字? name()是最終方法,因此無法覆蓋它,因此比toString更好。

當您使用關鍵字“枚舉”時,將通過擴展java.lang.Enum創建一個類。 java.lang.Enum中的一種方法是'public final String name()'。 此方法以字符串形式返回枚舉的確切聲明 如果需要,可以重寫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 */ 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM