Java泛型在Eclipse中编译,但不在javac中编译 [英] Java generics compile in Eclipse, but not in javac

查看:292
本文介绍了Java泛型在Eclipse中编译,但不在javac中编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不发现我的项目中有Java代码,它在Eclipse中编译和运行良好,但在javac中抛出一个编译错误。



自包含片段:

  import java.util.HashSet; 
import java.util.Set;

public class Main {

public static void main(String [] args){
Set< Integer> setOfInts = new HashSet< Integer>();
设置< Object> setOfObjects = covariantSet(setOfInts);
}

public static< S,T extends S>设置< S> covariantSet(Set< T> set){
return new HashSet< S>(set);
}

}

javac中的编译返回: p>

  Main.java:10:不兼容的类型
found:java.util.Set< java.lang.Integer>需要
:java.util.Set< java.lang.Object>
设置< Object> setOfObjects = covariantSet(setOfInts);
^

此错误现在可以防止在Maven中构建项目。由于Eclipse编译器被构建为更加宽容,所以现在我必须假定上述代码片段的定义和用法,静态方法是无效的Java?

解决方案

似乎Sun的1.6 JDK不能推断出正确的类型。以下内容似乎适用于我的机器:

  Set< Object> setOfObjects = Main。< Object,Integer> covariantSet(setOfInts); 

请注意,您必须调用静态方法以类名前缀


I had to discover I have Java code in my project, which compiles and runs fine in Eclipse, but throws a compilation error in javac.

A self-contained snippet:

import java.util.HashSet;
import java.util.Set;

public class Main {

    public static void main(String[] args) {
    Set<Integer> setOfInts = new HashSet<Integer>();
    Set<Object> setOfObjects = covariantSet(setOfInts);
    }

    public static <S, T extends S> Set<S> covariantSet(Set<T> set) {
    return new HashSet<S>(set);
    }

}

Compilation in javac returns:

Main.java:10: incompatible types
found   : java.util.Set<java.lang.Integer>
required: java.util.Set<java.lang.Object>
    Set<Object> setOfObjects = covariantSet(setOfInts);
                                           ^

This error now prevents building the project in Maven. As the Eclipse compiler is built to be more tolerant, I now have to assume the definition and usage of snippets as above static method is no valid Java?

解决方案

It seems that Sun's 1.6 JDK can't infer the correct type. The following seems to work on my machine:

Set<Object> setOfObjects = Main.<Object, Integer>covariantSet(setOfInts);

Note that you must invoke the static method prefixed with the class name

这篇关于Java泛型在Eclipse中编译,但不在javac中编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆