有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

“F obj”中的F替换为Factory时引发java Why类型不匹配错误。编译时F是什么

“F obj”中的F替换为Factory时引发类型不匹配错误的原因。什么是编译时的F,是对象还是编译时的F

interface Factory<T>
{
    T create();
}

class FirstClass<T>
{
    T x;
    <F extends Factory<T>> FirstClass(F obj)// Error will be thrown when F in (F obj)                                                  
                                            // is replaced with Factory. Error will be
                                            // cannot convert from "Object to T"
    {
        x = obj.create();
    }
}


class integerFactory implements Factory<Integer>
{

    @Override
    public Integer create() {

        return 1000;
    }

}

public class testGenerics {

    public static void main(String[] args) {
        new FirstClass<Integer>(new integerFactory());
    }

}

共 (1) 个答案

  1. # 1 楼答案

    编译错误是针对语句x = obj.create();

    这是因为Factory是一个raw type

    The reference type that is formed by taking the name of a generic type declaration without an accompanying type argument list.

    原始类型是其参数化类型的erasure

    类型变量(如Tis its left-most bound的擦除:

    If no bound is declared for a type variable, Object is assumed.

    因此,原始类型Factory的方法create返回Object

    我们不知道T中有什么FirstClass<T>,所以我们不知道Object是否可以分配给它

    另见: