I have some code maintaining a map of proto enums to their fully qualified descriptor names like so:
class EnumRegistry {
Map<String, Class<? extends Enum<?>>> ENUM_DESCRIPTOR_MAP = ImmutableMap.of(
Status.getDescriptor().getFullName(),
Status.class,
// ... other enums
);
public static Class<? extends Enum<?>> getEnumClass(String enumTypeName) {
return checkNotNull(ENUM_DESCRIPTOR_MAP.get(enumTypeName), "Unsupported enum type");
}
}
I have another bit of code that needs to pass the enum class to a method with this signature:
class OtherClass {
// Gets some stored enum value
public <T extends Enum<T>> T getEnum(Class<T> clazz) {
//... some work
}
}
The idea form of this code would look like:
String enumDescriptor = "some.package.Status"
OtherClass other = new OtherClass();
other.getEnum(EnumRegistry.getEnumClass(enumDescriptor));
This is not happy code with an error something like:
method getEnum in class package.Other cannot be applied to given types;
required: java.lang.Class<T>
found: java.lang.Class<capture#1 of ? extends java.lang.Enum<?>>
reason: inference variable T has incompatible bounds
equality constraints: capture#2 of ? extends java.lang.Enum<?>
upper bounds: java.lang.Enum<T>javac(compiler.err.cant.apply.symbol)
I have a workaround using a helper method that solves the compiler by introducing a helper method:
public void doWork() {
String enumDescriptor = "some.package.Status";
OtherClass other = new OtherClass();
getEnumValue.getEnumValue(enumDescriptor, other);
}
@SuppressWarnings("unchecked")
private <T extends Enum<T>> T getEnumValue(String enumDescriptor, OtherClass other) {
Class<T> enumClass = (Class<T>) SpannerEnumDescriptorRegistry.getEnumClass(enumDescriptor);
return other.getEnum(enumClass);
}
My question is, why does the work-around quiet the error? Is there a more intuitive way to communicate to the compile the enum class’s type when making hte call to OtherClass.getEnum(…)?