Java generics compile in Eclipse, but not in javac(Java 泛型在 Eclipse 中编译,但在 javac 中不编译)
问题描述
我不得不发现我的项目中有 Java 代码,它在 Eclipse 中编译和运行良好,但在 javac 中引发编译错误.
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.
一个独立的片段:
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);
}
}
javac 中的编译返回:
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);
^
此错误现在会阻止在 Maven 中构建项目.由于 Eclipse 编译器被构建为更宽容,我现在不得不假设上面的片段的定义和使用静态方法是无效的 Java?
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?
推荐答案
好像Sun的1.6 JDK无法推断出正确的类型.以下似乎适用于我的机器:
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 中不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 泛型在 Eclipse 中编译,但在 javac 中不编译
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01