假设我的应用程序中有以下类:
基类:
public abstract class Animal {}
子类
public class Dog extends Animal {
public void bark() {
System.out.println("woof");
}
}
来自第三方库的类:
public class ThirdPartyLibrary /* *cough* Hibernate *cough* */{
public List find() {
return new ArrayList() {
// fetched from the db in the actual app of course
{
add(new Dog());
add(new Dog());
add(new Dog());
}
};
}
}
还有一个实用程序类:
public class Util {
public <E extends Animal> E findUnique(List<E> animals) {
return animals.isEmpty() ? null : animals.get(0);
}
/**
* @param args
*/
public static void main(String[] args) {
Dog d = new Util().findUnique(new ThirdPartyLibrary().find());
d.bark();
}
}
Eclipse 编译器发出以下警告:
- Type safety: The expression of type List needs unchecked conversion to conform to List
- Type safety: Unchecked invocation findUnique(List) of the generic method findUnique(List) of type Util
但是使用 Sun 的 javac 编译时构建失败,并出现错误:
incompatible types
[javac] found : Animal
[javac] required: Dog
[javac] Dog d = new Util().findUnique(new ThirdPartyLibrary().find());
[javac] ^
除了显式转换为 (List<Dog>)
之外,我还能做些什么来使这段代码在 javac 中编译吗?在调用 findUnique 之前?
最佳答案
不,您无能为力,并且 Eclipse 中一定有什么可疑的事情发生,因为 Eclipse 也无法将其编译(作为 Java 代码)。由于传递给 findUnique() 的列表是原始类型,因此编译器无法确定 E
的内容。应该在 public <E extends Animal> E findUnique(List<E> animals)
。因此E
本质上变成?
,而您想要做的基本上是这样的:
List<? extends Animal> l = new ArrayList<Animal>();
Dog dog = l.get(0);
很明显,这永远行不通。接近实现此目的的唯一方法是添加一个方法参数,使 E
具有独特的值(value)。像这样的事情会起作用:
public <E extends Animal> E findUnique(List animals, Class<E> type) {
return animals.isEmpty() ? null : (E) animals.get(0);
}
关于java - 泛型 - Eclipse 编译器发出警告,javac 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747052/