2

I have a problem, I need to resolve type of class which replaced the generic type parameter. Here is the code:

public class EnumSetPlay {

    private enum SomeEnum {ONE, TWO}

    private static class Test<E extends Enum> {
        private Class<E> clazz = (Class<E>) GenericTypeResolver.resolveTypeArgument(getClass(), Test.class);;

        public void test() {
            for (E element : EnumSet.allOf(clazz))
                System.out.println(element);
        }
    }

    public static void main(String... args) {
        new Test<SomeEnum>().test();
    }
}

I need to get class type SomeEnum. I trying to use spring GenericTypeResolver class, but I have next error:

error: incompatible types
required: E
found:    Object
where E is a type-variable:
E extends Enum declared in class Test

user1289877
  • 279
  • 6
  • 12

3 Answers3

1

I don't think that this is possible due to type erasure, which removes the type information. Some links:

Community
  • 1
  • 1
nwinkler
  • 52,665
  • 21
  • 154
  • 168
1

Try this:

    public class EnumSetPlay {

    private enum SomeEnum {
        ONE, TWO
    }

    private static class Test<E extends Enum<E>> {

        @SuppressWarnings("unchecked")
        private Class<E> clazz = (Class<E>) GenericTypeResolver.resolveTypeArgument(getClass(), Test.class); ;

        public void test() {
            for (E element : EnumSet.allOf(clazz))
                System.out.println(element);
        }
    }

    private static class DummyTest extends Test<SomeEnum> {
    }

    public static void main(String... args) {
        new DummyTest().test();
    }

}
0

What you are trying to do is simply not possible because of type-erasure as explained in other answers. If you to achieve what you are trying to do, the only solution is to pass the class as a parameter of the constructor:

public class EnumSetPlay {

    private enum SomeEnum {ONE, TWO}

    private static class Test<E extends Enum<E>> {
        private Class<E> clazz ;

        public Test(Class<E> clazz) {
            this.clazz = clazz;
        }

        public void test() {
            for (E element : EnumSet.allOf(clazz))
                System.out.println(element);
        }
    }

    public static void main(String... args) {
        new Test<SomeEnum>().test();
    }
}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117