开发者

Java covariant return types not working for overriding methods of an enum instance?

I spent quite a while with Google to find some information on this topic, but results relating to both Java enums and covariant return types were pretty much non-existent.

So: is it possible to use covariant return types with enum methods where you define a method in the enum class and then override it in the instances, like so:

package enumcovariance.test;

public enum CovariantEnum {

    INT_INSTANCE(new Integer(3)) {
        @Override
        public Integer getData () {
            return (Integer) super.getData();
        }
    },

    STR_INSTANCE("Hello world") {
        @Override
        public String getData () {
            return (String) super.getData();
        }
    };

    private final Object data;

    private CovariantEnum(Object data) {
        this.data = data;
    }

    public Object开发者_开发百科 getData () {
        return data;
    }

}

And then to take advantage of the covariance like so:

package enumcovariance.test;

import org.junit.Test;


public class CovariantEnumTest {

    @Test
    public void intEnumTest () {
        Integer i = CovariantEnum.INT_INSTANCE.getData();
    }

    @Test
    public void strEnumTest() {
        String s = CovariantEnum.STR_INSTANCE.getData();
    }

}

In this case the compiler is fine with my enum definition, but the test case fails to compile, saying Object cannot be converted to Integer (or String). Apparently the compiler only looks at the base definition of the method, not the overriding method. With a different enum definition I had the base method abstract, but that still didn't work.

I'm thinking it's something complex to do with the way enums are transformed during the compile process that prevents it from working, but I want to be sure it's not just me doing something silly.

Note that this test case is admittedly very contrieved, in my actual enum this functionality would be more useful. I can post it if necessary.


The type of CovariantEnum.INT_INSTANCE is CovariantEnum which returns Object from getData.

Unfortunately, you can't make the enum type generic either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜