Search code examples
javagenericsenumset

How to invoke EnumSet#(all|none)Of with a Class<?>?


I need to invoke EnumSet#nonOf or EnumSet#allOf with an unknown type of class.

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        final EnumSetOfAll annotation = parameterContext.getParameter().getAnnotation(EnumSetOfAll.class);
        final Class<?> value = annotation.value();
        if (!value.isEnum()) {
            throw new ParameterResolutionException("value(" + value + ") is not an enum");
        }

        // How can I return the result of EnumSet#(all|none)Of invoked with value?

    }


Solution

  • First, change the type of your annotation's value() to Class<? extends Enum>.

    Now you can do:

    final Class<? extends Enum> value = annotation.value();
    

    Now this can be passed to allOf and noneOf:

    EnumSet<?> set = EnumSet.allOf(value);