[英]Java enum instances with different number of arguments
我有沒有辦法讓Java中的Enum接受不同數量的參數,以便在不使用varargs的情況下實現這一點。
public enum ValueType {
LITERAL() {
@Override
String getRepresentation(String... args) {
return MvelStringUtil.representAsLiteral(args[0]);
}
},
NUMBER() {
@Override
String getRepresentation(String... args) {
return args[0];
}
},
//converts a string representation of a date to a java.util.Date representation, because this is what is required
DATE() {
@Override
// should have two params, 1- date in string, 2- format of the passed string
String getRepresentation(String... args) {
// DateUtil.parse accepts dateInString and dateFormat.
return DateUtil.parse(args[0], args[1]).toString();
}
};
abstract String getRepresentation(String... args);
}
這里,LITERAL和NUMBER只接受一個參數,即目標值,而DATE實例接受兩個。 我經歷了幾個問題才發現使用Generics無法實現這一點,因為枚舉並不能真正支持泛型。
此外,從設計的角度來看,我可能只是沒有Enum中的所有類型而是將它們放在具有一些變通方法的類中,請記住,需要從json解組的ValueType實例和getRepresentation方法將在unmarshalled上調用枚舉實例以獲取目標值的實際表示。
這是不可能的,因為LITERAL,NUMBER和DATE符合枚舉ValueType的接口。 如果可能的話,這里會違反類型安全:
LITERAL()
{
@Override
String getRepresentation(String args) {
return MvelStringUtil.representAsLiteral(arg);
}
}
...
ValueType x = ValueType.LITERAL;
x.getRepresentation("a","b"); // the compiler could not know whether this is syntactically correct
正如其他答案所說,這是不可能的。 目標是確保給定類型的參數數量不會錯誤,這樣調用代碼中的錯誤很快就會出現,對吧?
我將在每個getRepresentation方法實現中進行簡單驗證 。 檢查數組長度, 如果不正確則拋出異常 。
這樣,有效性規則就會與主題保持一致,這是可讀的。 你不會在編譯時知道錯誤,但至少你會在運行時早期就知道錯誤。
廣告設計視角 - 我會保持枚舉。 大量的類型是有限的,在編譯時已知,並且通過快速檢查枚舉,每個人都會知道有什么可能性......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.