与泛型类型的动态绑定
我需要动态绑定参数类型(列表),但我不明白...... 这是我的类的概述:
public abstract interface SettingsField<A> extends Window
然后我有一些实现 SettingsField 的类:
public class StringSettingsField implements SettingsField<String>
public class MapSettingsField<K, V> implements SettingsField<Map<K, V>>
第一个非常简单,但例如第二个有点棘手......所以我想创建一个返回 SettingsFileds 的工厂。我想使用动态绑定为我想要放入其中的每个对象获取正确的 SettingsWindow 。 所以我重载了以下方法 getField 。 对于字符串来说它很容易:
public SettingsField<String> getField(String x){
return new StringSettingsField();
}
但是对于地图我遇到了一些麻烦......
public SettingsField<Map<? extends String, ?>> getField(Map<? extends String, ?> x){
return new MapSettingsField();
}
密钥始终是一个字符串就是一个例子(可能是?也) 但现在编译器给了我警告
MapSettingsField 是原始类型。对泛型类型 MapSettingsField 的引用应该参数化
,但我如何在这里做到这一点?问题是只是使用 Map 无效,因为 java 中的 f-generic 存在一些问题(即使 B 是 A 的子类型,List 也不是 List 的隐式子类型)
有什么提示吗?提前致谢!
i need to bind dynamic a parametic type (List) but i dont get it right...
here is an overview of my classes:
public abstract interface SettingsField<A> extends Window
then i have some classes which implements SettingsField:
public class StringSettingsField implements SettingsField<String>
public class MapSettingsField<K, V> implements SettingsField<Map<K, V>>
the first is real simple, but eg the second is a little bit tricky... so i want to make a factory which returns SettingsFileds. I want to use dynamic binding to get the right SettingsWindow for each Object i want to put in there.
so i overload a method getField the following.
for String its quite easy:
public SettingsField<String> getField(String x){
return new StringSettingsField();
}
but for map i have some trouble...
public SettingsField<Map<? extends String, ?>> getField(Map<? extends String, ?> x){
return new MapSettingsField();
}
that the key is always a string is an exampe (could be ? also)
but now the compiler gives me the waring that
MapSettingsField is a raw type. References to generic type MapSettingsField should be parameterized
but how i can do this here? the problem is just use Map is not valid, because of some problem with f-generic in java (List is not implicit subtype of List even if B is subtype of A)
any hints? thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IIUYC,你需要
顺便说一句,
extends String
没有多大意义,因为 String 是最终的。然而,我会选择类似的东西
你也可以声明 K 有界,例如
或其他。
IIUYC, you need
Btw.,
extends String
doesn't make much sense as String is final.However, I'd go for something like
You could declare K as bounded, too, e.g.
or whatever.