gpt4 book ai didi

java - 返回子类

转载 作者:行者123 更新时间:2023-12-01 13:31:44 24 4
gpt4 key购买 nike

抱歉,标题含糊不清,我不太确定如何解释我的问题。

我正在致力于创建实体组件系统 (ECS),但遇到了一些障碍。我有一个名为 getComponent() 的函数,它的工作是使用给定的组件类(在本例中为 Name 组件)从给定实体获取特定组件。到目前为止,我可以匹配 componentcomponentClass 以返回正确的组件。这是函数:

public static Component getComponent(int id, Class<? extends Component> componentClass){
ArrayList<Component> entity = getEntity(id);
for(Component component : entity){
if(component.getClass() == componentClass){
return component;
}
}

return null;
}

我的问题在于返回组件的类型转换。我举一个简单的例子。在管理所有 Name 组件的 Namer 类中,我想循环实体数据库,获取实体的 Name 组件,执行逻辑,然后继续。问题是,为了从 Name 获取数据,我必须像这样转换组件:

int entity = i;
Name n = (Name)Game.getComponent(entity, Name.class);

我希望能够做到这一点:

int entity = i;
Name n = Game.getComponent(entity, Name.class);
n.test = "Bob Binley"

我知道这是一个奇怪的“问题”,因为它工作得很好,但我对这样的代码感到不舒服。考虑到 getComponent() 函数将被大量调用,使用大量不同的 Component,我宁愿不必担心每次都转换组件类型我想使用它。

谢谢。

最佳答案

您可以做到这一点,您只需稍微更改方法签名中的泛型即可:

public static <T extends Component> T getComponent(int id, Class<T> componentClass){

现在 Generics 知道您的 getComponent 方法返回类型为 T 的对象,并且在调用 getComponent 时无需进行强制转换 - 尽管您的 getComponent 实现可能仍需要在内部进行强制转换。

关于java - 返回子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21530603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com