有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java javac错误:不可转换的泛型类型?

还有其他几个关于泛型编译OK w/Eclipse编译器而不是javac(即Java: Generics handled differenlty in Eclipse and javacGenerics compiles and runs in Eclipse, but doesn't compile in javac)的问题——不过这看起来有点不同

我有一门enum课:

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

我还有一个类,它有一个方法,可以接收从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行,另一个在铸造行:

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]                                                  ^

为什么会发生这种情况,我如何才能绕过这个问题,使它能够正确编译


共 (4) 个答案

  1. # 1 楼答案

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

    @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;
        ...
    

    这很难看,但它很管用

  2. # 2 楼答案

    我有一个类似的问题,并从jdk1升级。6.0_16至jdk1。6.0_23,它没有任何代码更改就消失了

  3. # 3 楼答案

    也许是因为您已经声明E是扩展Enum的东西<;E>;。我不能说我完全理解它,但它似乎将类型集限制为一些不包含LogEvent的子集。出于某种原因打字。或者可能只是编译器中的一个bug。如果有人能更清楚地解释,我会很高兴,但以下是你能做的:

    public <E extends Enum<?>> void postEvent(E code) 
    {
        if (code instanceof LogEvent.Type)
        {
            LogEvent.Type scode = (LogEvent.Type)code;
            ...
        }
        ...
    

    这是有效的,它比仅仅铸造一个物体更优雅

  4. # 4 楼答案

    为了使用instanceof,两个操作数必须继承/实现同一个类/接口
    E就是不能投给LogEvent。类型

    我不知道你的完整方法是什么样子的,但这应该通过使用接口而不是泛型来解决你的问题

    public interface EventType { }
    public class LogEvent  {
        public enum Type implements EventType {}
    }
    
    public void postEvent(Context context, EventType code, Object additionalData) {
        if(code instanceof LogEvent.Type) {
        }
    }