[英]Generic return Method to be defined by generic parameter in method
I have an interface in Java: 我在Java中有一个接口:
public interface IElement{
public String getId();
public String getName();
/***
* adds an IElement to this elements children
* @param child
*/
void getAddChild(IElement child);
/***
* returns all children
* @return
*/
Collection<IElement> getChildren( );
/***
* returns all children which match the Class of the passed IElement
* @param eType - the class type to match
*/
Collection<IElement> getChildren( Class<? extends IElement> eType);
}
The idea is that an IElement
may contain a collection of other IElement
s. 这个想法是一个
IElement
可以包含其他IElement
的集合。
I need the method Collection<IElement> getChildren(Class<? extends IElement> eType)
to return a collection of matching siblings. 我需要方法
Collection<IElement> getChildren(Class<? extends IElement> eType)
返回匹配兄弟姐妹的集合。
Say I had a three classes which all extend IElement
. 说我有三个类,所有类都扩展了
IElement
。 One was called Room
, another was called Box
( box1
, box2
, box3
), and another was called Shelve
( shelve1
) 一个叫做
Room
,另一个叫做Box
( box1
, box2
, box3
),另一个叫做Shelve
( shelve1
)
Now with an instance of a Room
I can do the following: 现在,有了一个
Room
实例,我可以执行以下操作:
room1.addChildren(box1);
room1.addChildren(box2);
room1.addChildren(shelve1,sheleve2);
room1.addChildren(box3);
Now I have a Room
( room1
) with three different boxes in it and a Shelve
( shelve1
). 现在我有一个
Room
( room1
,在它和三个箱) Shelve
( shelve1
)。 Now I would like to get all Box
objects inside room1
using the Collection<IElement> getChildren(Class<? extends IElement> eType);
现在,我想使用
Collection<IElement> getChildren(Class<? extends IElement> eType);
获取room1
内的所有Box
对象Collection<IElement> getChildren(Class<? extends IElement> eType);
method, as in room1.getChildren(Box.class)
. 方法,如在
room1.getChildren(Box.class)
。 However, the method only returns a collection of IElement
s. 但是,该方法仅返回
IElement
的集合。 I would like it to return Collection<Box>
. 我希望它返回
Collection<Box>
。 If I passed Shelve
then it should return a collection of Shelve
objects. 如果我通过了
Shelve
那么它应该返回Shelve
对象的集合。
Is this possible? 这可能吗? And if so, how do you do it?
如果是这样,您该怎么做? I know this seems odd, but I have a lot of different objects which can all hold other Elements, and I need a quick and easy way to filter for different types.
我知道这似乎很奇怪,但是我有很多可以容纳其他Elements的不同对象,并且我需要一种快速简便的方法来过滤不同类型的对象。
You can declare a generic method with a named generic type, instead of using a wildcard. 您可以使用命名的泛型类型声明泛型方法,而不使用通配符。
<E extends IElement> Collection<E> getChildren(Class<E> eType);
That way, the generic type of the collection you get out will match the class that you passed in. 这样,您获取的集合的通用类型将与您传入的类匹配。
Your implementation will have to construct and return a collection of the appropriate generic type for its argument. 您的实现将必须构造并为其参数返回适当的泛型类型的集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.