未经检查的调用和未经检查的分配java工厂泛型

时间:2018-05-22 19:36:41

标签: java generics warnings

考虑以下情况:

public abstract class A {}

public class B extends A {}

public interface Provider<T extends A> {
    List<String> list(T param);
}

public class ProviderB implements Provider<B> {
    @Override
    public List<String> list(B param) {
        return Collections.singletonList("ProviderB");
    }
}


public class Factory {
    public static Provider get(int x) {
        if (x == 1)
            return new ProviderB();
        throw new RuntimeException("Not supported");
    }
}


public class Main {
    public static void main(String[] args) {
        Provider provider = Factory.get(1);
        A a = new B();
        List<String> result = provider.list(a);
    }
}

List<String> result = provider.list(a);的主页,我得到了:

Unchecked call to list(T) ..
Unchecked assignment java.util.List .. Reason 'provider' has raw type.

我确实知道一些关于泛型中类型擦除的基本内容。你会如何解决警告?

修改 实际上主要看起来像这样:

public static void main(Map<Integer, ? extends A> types) {
        for (Map.Entry<Integer, ? extends A> entryType : types.entrySet()) {
            Provider provider = Factory.get(entryType.getKey());
            List<String> result = provider.list(entryType.getValue());
        }
    }

0 个答案:

没有答案