This question already has answers here:
What is a raw type and why shouldn't we use it?
                                
                                    (15个答案)
                                
                        
                        
                            Create instance of generic type in Java?
                                
                                    (27个答案)
                                
                        
                                5个月前关闭。
            
                    
在下面的示例中,我似乎无法摆脱未经检查的警告(除非加以抑制)。如您在“ 2”中看到的。指定类型会导致编译错误。

压制是这里唯一的选择吗?

static class Cat { }

static class CatGiver<T extends Cat> {

    T cat;

    CatGiver(T cat) {
        this.cat = cat;
    }

    static <T extends Cat> CatGiver<T> get() {
        // 1. Unchecked assignment warning
        return new CatGiver(new Cat());

        // 2. Compile error on 'new Cat()' "T cannot be applied to Cat..."
        // return new CatGiver<T>(new Cat());
    }
}

最佳答案

首先,您要创建原始类型。您需要指定类型。其次,您的静态方法'T'不是变量,您只能返回Cat。

static CatGiver<Cat> get() {

    return new CatGiver<Cat>(new Cat());

}


通过将猫的实例或类作为答案传递给duplicate question,可以使猫成为通用类型。

static <T extends Cat> CatGiver<T> get(T cat){
    return new CatGiver<>(cat);
}


然后应从参数隐式获取T。 (我还没有测试。)

08-05 18:51