在我目前正在编写的游戏中,我的清单中有一个Collectable
对象列表。当我激活其中一个对象时,有些对象需要另一个Collectable
对象来处理。现在,在我的UI中,我展示了原始对象可能使用的所有可能的候选Collectable
对象。为此,我检查对象是否是接口的实例。但是该接口因对象而异。 UI称为ItemSelector
,由主UI调用。
通过使构造函数将ItemSelector
作为参数来构造class<T> selectionCriteria
。
<T> ItemSelector(Class<T> selectionCriteria){
// ... Do work.
}
然而,这意味着当我创建这个类的对象时,我必须根据原始对象的类型对switch case
语句中可能的所有可能的接口进行硬编码。我想做什么是每个Collectable
对象中都有一个方法(Collectable
接口将有一个getSelectionCriteriaInterface()
方法,将由具体类覆盖)将返回它用作的接口作为selectionCriteria。
我如何实现这一目标。 希望快速回复, 感谢。
答案 0 :(得分:1)
像这样:
interface Collectable {
...
Class<?> getSelectionCriteriaInterface();
}
可能的实施:
public Class<?> getSelectionCriteriaInterface() {
return MyInterface.class;
}
然后在检查时,例如:
Collection<Collectable> allItems = ...;
Collectable c = ...;
List<Collectable> filtered = allItems.stream()
.filter(c.getSelectionCriteriaInterface()::isInstance)
.collect(Collectors.toList());