javac 错误:具有泛型的不可转换类型? [英] javac error: inconvertible types with generics?

查看:34
本文介绍了javac 错误:具有泛型的不可转换类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有其他几个 SO 问题讨论泛型编译可以使用 Eclipse 的编译器而不是 javac(即 Java:泛型在 Eclipse 中处理差异)和 javac泛型在 Eclipse 中编译和运行,但不能在 javac 中编译) -- 但是这个看起来有点不同.

There are several other SO questions talking about generics compiling OK w/ Eclipse's compiler but not javac (i.e. Java: Generics handled differenlty in Eclipse and javac and Generics compiles and runs in Eclipse, but doesn't compile in javac) -- however this looks like a slightly different one.

我有一个 enum 类:

public class LogEvent {
   public enum Type {
       // ... values here ...
   }
   ...
}

我有另一个类,它的方法接受从 Enum 派生的任意类型的对象:

and I have another class with a method that takes in arbitrary objects of types descended from Enum:

@Override public <E extends Enum<E>> void postEvent(
    Context context, E code, Object additionalData) 
{
    if (code instanceof LogEvent.Type)
    {
        LogEvent.Type scode = (LogEvent.Type)code;
    ...

这在 Eclipse 中运行良好,但是当我使用 ant 进行干净构建时,我收到一对错误,一个在 instanceof 行上,另一个在铸造线:

This works fine in Eclipse, but when I do a clean built with ant, I am getting a pair of errors, one on the instanceof line, the other on the casting line:

443: inconvertible types
    [javac] found   : E
    [javac] required: mypackage.LogEvent.Type
    [javac]         if (code instanceof LogEvent.Type)
    [javac]             ^

445: inconvertible types
    [javac] found   : E
    [javac] required: com.dekaresearch.tools.espdf.LogEvent.Type
    [javac]             LogEvent.Type scode = (LogEvent.Type)code;
    [javac]                                                  ^

为什么会发生这种情况,我该如何解决这个问题以使其正确编译?

Why does this happen, and how can I get around this problem so it will compile properly?

推荐答案

我不知道为什么会这样,但解决方法很简单:

I don't know why it's happening, but a workaround is easy:

@Override public <E extends Enum<E>> void postEvent(
    Context context, E code, Object additionalData) 
{
    Object tmp = code;
    if (tmp instanceof LogEvent.Type)
    {
        LogEvent.Type scode = (LogEvent.Type)tmp;
    ...

它很丑,但它有效......

It's ugly, but it works...

这篇关于javac 错误:具有泛型的不可转换类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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