javac error: inconvertible types with generics?

后端 未结 4 1886
醉梦人生
醉梦人生 2020-12-24 02:33

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 a

相关标签:
4条回答
  • 2020-12-24 02:53

    Perhaps it is because you've declared E as something that extends Enum<E>. I can't say I understand it completely, but it looks like it limits the set of types to some subset that can't include LogEvent.Type for some reason. Or maybe it's just a bug in the compiler. I'd be happy if someone could explain it more clearly, but here is what you can do:

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

    This works and it is more elegant than just casting to an Object.

    0 讨论(0)
  • 2020-12-24 02:59

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

    0 讨论(0)
  • 2020-12-24 03:02

    In order to use instanceof both operands have to inherit/implement the same class/interface.
    E just can't be cast to LogEvent.Type

    I don't know what your full method looks like, but this should solve your issue by using interfaces and not Generics.

    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) {
        }
    }
    
    0 讨论(0)
  • 2020-12-24 03:05

    I had a similar problem and upgraded from jdk1.6.0_16 to jdk1.6.0_23 and it went away without any code changes.

    0 讨论(0)
提交回复
热议问题