[英]Get subclass instance from list of superclasses or interfaces
( This question is similar to mine but I felt that they were different enough that I could create a new one). ( 这个问题类似于我的问题,但是我觉得它们足够不同,因此我可以创建一个新的)。
Basically in my small 3D game all of my entities are made up of many different components, one for textures, one for movement etc. All of these sub-components inherit from the interface "Component". 基本上,在我的小型3D游戏中,我所有的实体都是由许多不同的组件组成的,一个用于纹理,一个用于运动等。所有这些子组件都继承自“组件”接口。 Up until now I've used methods like this; 到目前为止,我已经使用过类似的方法。
public MovementComponent getMovementComponent() {
for (Component c : components) {
if (c instanceof MovementComponent)
return (MovementComponent) c;
}
return null;
}
To get an instance of a certain component. 获取某个组件的实例。 But now I wish to change this to a more general method that can get any type of component from my list of components. 但是现在我希望将其更改为更通用的方法,该方法可以从我的组件列表中获取任何类型的组件。 I tested doing something like this; 我测试过做这样的事情;
public Component getComponentType(Class component) {
for (Component c : components) {
if (c.getClass() == component)
return c.getClass().cast(c);
}
return null;
}
But even though I cast the result this always returns an """instance""" of the interface, never an instance of a sub-component, which means I still have to cast it to the appropriate type. 但是,即使我强制转换结果,它始终会返回接口的““” instance“”“,而不是子组件的实例,这意味着我仍然必须将其强制转换为适当的类型。 Basically I wish for a method that can: 基本上,我希望有一种方法可以:
I feel like I'm on the right track here but I can't get it to work. 我觉得自己在正确的轨道上,但是无法正常工作。 Thanks for your responses and feedback. 感谢您的答复和反馈。
You need something like 你需要类似的东西
public <T extends Component> T getComponentType(Class<T> component) {
...
return (T) c;
}
Method declaration tells that it will return a component of the same type passed in parameters. 方法声明表明它将返回传入参数中相同类型的组件。
Call it like this: 这样称呼它:
MovingComponent mc = smth.getComponentType(MovingComponent.class);
You need to use a generic parameter, something like this: 您需要使用通用参数,如下所示:
public <C extends Component> C getComponentType(Class<C> subclass) {
for (Component c : components) {
if (subclass.isInstance(c))
return subclass.cast(c);
}
return null;
}
Thank to isInstance
, this also finds any further subclass of the given parameter. 感谢isInstance
,它也可以找到给定参数的任何其他子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.