Java generics compile in Eclipse, but not in javac

后端 未结 5 1361
面向向阳花
面向向阳花 2020-12-16 14:49

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:

5条回答
  •  北海茫月
    2020-12-16 15:28

    You are right. This problem indeed exists. Eclipse does not use javac. It uses its own compiler.

    Actually javac is "right". Generics are erasures. Type S is not included into your byte code, so jvm does not have enough information about the return type at runtime. To solve the problem change the method prototype as following:

    public static Set covariantSet(Set set, Class returnType)

    Now the return type is passed to the method at runtime and compiler should not complain.

提交回复
热议问题