javac error: inconvertible types with generics?

点点圈 提交于 2019-11-29 22:21:50

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

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.

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.

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) {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!