【问题标题】:Getting a component by it's Generic Type通过它的通用类型获取组件
【发布时间】:2012-02-18 09:30:41
【问题描述】:

我要做的是创建一个方法,允许用户搜索 GameComponents 列表以找到他们传入的任何类的 GameComponent。

我完全不知道如何做到这一点。有什么想法吗?

这是我迄今为止尝试过的。我尝试了很多不同的方法来做到这一点,但我不断得到 classDude 无法解析为一种类型。提前致谢。

public GameComponent<?> getComponentOfType(Class<Object> classDude)
    {

        for(GameComponent<?> gC : mComponentList)
        {
            if(gC instanceof classDude)
            {

            }
        }

    }

【问题讨论】:

    标签: java generics search components


    【解决方案1】:

    听起来像你想要的:

    public <T extends GameComponent<?>> T getComponentOfType(Class<T> classDude)
    {
        for(GameComponent<?> gC : components)
        {
            if(classDude.isInstance(gC))
            {
                return classDude.cast(gC);
            }
        }
        return null;
    }
    

    或者不让它通用:

    public GameComponent<?> getComponentOfType(Class<?> classDude)
    {
        for(GameComponent<?> gC : components)
        {
            if(classDude.isInstance(gC))
            {
                return (GameComponent<?>) classDude.cast(gC);
            }
        }
        return null;
    }
    

    换句话说,您缺少的是Class.isInstanceClass.cast 方法。

    【讨论】:

    • 如果我想让函数本身看起来像这样,我会怎么做:
    • getComponent();
    • @user1159418:你不能——这根本不是你在 Java 中调用泛型方法的方式,你必须提供类,否则类型擦除会打击你。不过你可以使用getComponent(TextureComponent.class)
    • 非常感谢您抽空先生!
    猜你喜欢
    • 2014-11-13
    • 1970-01-01
    • 2023-03-20
    • 2017-02-06
    • 2011-03-12
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2013-04-02
    相关资源
    最近更新 更多