不兼容的类型。必需:T,找到T。为什么?

时间:2019-05-18 14:03:29

标签: java dictionary generics hashmap

我正在尝试使用泛型构建服务定位器,并且编译器在以下位置收到警告 objects.put(klass, value) 它说不兼容的类型,必填:T。找到:T。

public class SimpleServiceLocator <T> implements ServiceLocator<T> {
    private HashMap<Class, Factory> services = new HashMap<>();
    private HashMap<Class, T> objects = new HashMap<>();


    @Override
    public <T> void setService(Class<T> klass, Factory<T> factory) throws LocatorError {
        if (services.containsKey(klass)) throw new LocatorError();
        services.put(klass, factory);
    }



    @Override
    public <T> T getObject(Class<T> klass) throws LocatorError {
        if (services.containsKey(klass)) {
            Factory factory = services.get(klass);
            return (T) factory.create(this);
        } else if(objects.containsKey(klass)) {
            return (T) objects.get(klass);
        }
        throw new LocatorError();
    }

    @Override
    public <T> void setConstant(Class<T> klass, T value) throws LocatorError {
        if (objects.containsKey(klass)) throw new LocatorError();
        objects.put(klass, value);
    }
}

接口是:

public interface ServiceLocator <T>{
    <T> void setService(Class<T> klass, Factory<T> factory)
            throws LocatorError;

    <T> void setConstant(Class<T> klass, T value)
            throws LocatorError;

    <T> T getObject(Class<T> klass)
            throws LocatorError;
}

1 个答案:

答案 0 :(得分:1)

您已经定义了多个具有相同名称的泛型类型。

public class SimpleServiceLocator <T>

在类级别定义通用类型T

<T> void setService

在功能级别定义通用类型T

如果在函数内部使用T,则将使用函数定义中的T,这与用于声明HashMap的类型不同。