想用StandardCharsets.UTF_8 返回"UTF-8"這個字元,測試一下,三個方法toString() name() displayName(),均能返回"UTF-8",到底用哪個方法更健壯?
public final String name()
Returns this charset's canonical(正式的) name.
=========================================
public String displayName()
Returns this charset's human-readable(便於人類可閱讀的) name for the default locale.
The default implementation of this method simply returns this charset's canonical name. Concrete subclasses of this class may override this method in order to provide a localized display name.
==========================================
public final String toString()
Returns a string describing this charset.
==========================================
一分析,自然是name displayName比toString更合適,二選一,找區別自然選擇name,因為我是要給程式傳遞引數,而不是輸出給人機介面。
另外,找了一個最好的例證,jdk有這樣的用法:
package java.util.zip;
final class ZipCoder
private ZipCoder(Charset cs) {
this.cs = cs;
this.isUTF8 = cs.name().equals(StandardCharsets.UTF_8.name());
}
這些自己更放心啦。