2
votes

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

3
it is usually better to type with <E extends Enum<E>> - Guillaume Polet
I repaire that but now I have NullPointerException, because the clazz is null. - user1289877

3 Answers

1
votes

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
votes

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();
    }
}