[英]Java generics question with wildcards
Just came across a place where I'd like to use generics and I'm not sure how to make it work the way I want. 刚遇到一个我想使用泛型的地方,我不知道如何让它按照我想要的方式工作。
I have a method in my data layer that does a query and returns a list of objects. 我的数据层中有一个方法来执行查询并返回一个对象列表。 Here's the signature.
这是签名。
public List getList(Class cls, Map query)
This is what I'd like the calling code to look like. 这就是我想要的调用代码。
List<Whatever> list = getList(WhateverImpl.class, query);
I'd like to make it so that I don't have to cast this to a List<Whatever>
coming out, which leads me to this. 我想这样做,以便我不必将它转换为
List<Whatever>
出来,这导致我这样做。
public <T> List<T> getList(Class<T> cls, Map query)
But now I have the problem that what I get out is always the concrete List<WhateverImpl>
passed in whereas I'd like it to be the Whatever
interface. 但现在我遇到的问题是,我得到的东西总是具体的
List<WhateverImpl>
传入,而我希望它是Whatever
接口。 I tried to use the super keyword but couldn't figure it out. 我试图使用super关键字,但无法弄明白。 Any generics gurus out there know how this can be done?
那里的任何仿制药大师都知道如何做到这一点?
你需要像这样定义方法:
public <B, C extends B> List<B> getList(final Class<C> cls, final Map<?, ?> query)
The only way I can think this would work is like this: 我能想到的唯一方法就是这样:
public <T extends Whatever> List<? extends Whatever> get(Class<T> clazz, Map query) {
return new ArrayList<T>(); // do whatever it is you do here to return a List<T>
}
and then call it like: 然后称之为:
List<? extends Whatever> l = get(WhateverImpl.class, query);
for (Whatever w : l) {
// do something
}
You can't return List<Whatever>
directly since you won't be able to cast List<WhateverImpl>
to it inside the get method (they're not compatible). 您不能直接返回
List<Whatever>
,因为您将无法在get方法中将List<WhateverImpl>
为它们(它们不兼容)。
你有什么理由不能这样做吗?
public List<T> getList<T>(Map query)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.