[英]How to interface can extends 2 with that extends the same but with different generic parameters in java?
[英]How can I define in JAVA generic type that extends Map object with 2 generic parameters?
這是我的代碼:
public class Configuration <T extends Map<K,V>, K, V> {
public Map<K, V> fields;
public Configuration() {
this.fields = new T<K, V>(); // --> error: Type 'T' does not have type parameters
}
}
為什么不能用通用參數定義通用對象?
由於在Java中如何設計泛型(泛型信息僅在編譯時使用),因此您永遠無法在T
為類型參數的情況下new T()
。
一種可能的替代方法是執行以下操作:
public interface ConfigurationMapFactory<K, V> {
public Map<K, V> createMap();
}
public class Configuration <K, V> {
public Map<K, V> fields;
public Configuration(ConfigurationMapFactory<K, V> mapFactory) {
this.fields = mapFactory.createMap();
}
}
盡管在這種情況下,您可以輕松做到這一點-是否有理由不起作用?
public class Configuration <K, V> {
public Map<K, V> fields;
public Configuration(Map<K, V> fields) {
this.fields = fields;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.