java - 泛型 - Eclipse 编译器发出警告,javac 给出错误

标签 java

假设我的应用程序中有以下类:

基类:

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/

相关文章:

java - 有人用过solr5.5吗? Mysql包应该放在哪个目录下?

java - 在数据库中插入一个字符数组

java - 在不使用任何资源 xml 的情况下将 View (按钮、标签等)添加到动态 fragment

java - 如何配置多个 Quartz 单线程作业

java - IntelliJ + Spring Web MVC

java - 在 MANIFEST.MF 文件中找不到属性 'JCabi-Version'

java - MongoDB Java 驱动程序 - 在查找查询中使用存在投影

java - 我的登录按钮什么都不做

java - 获取所有 Android 联系人和详细信息并放入单个多维数组中

无法识别 Java 正则表达式空白