I'm working on a project running with JDK8 and we want to migrate it to OpenJDK11.
But, there is legacy code that creates enums dynamically at runtime (using reflection and sun.reflect.*
packages) :
public class EnumUtil {
static Object makeEnum(...) {
...
enumClass.cast(sun.reflect.ReflectionFactory.getReflectionFactory() .newConstructorAccessor(constructor).newInstance(params));
}
}
Or
// before, field is made accessible, the modifier too
sun.reflect.FieldAccessor fieldAccessor = sun.reflect.ReflectionFactory.getReflectionFactory().newFieldAccessor(field, false);
field.set(target, value);
For example, let's say we have the enum AEnum
:
public enum AEnum {
; // no values at compile time
private String label;
private AEnum (String label) {
this.label = label;
}
Then, we add enum values like this :
EnumUtil.addEnum(MyEnum.class, "TEST", "labelTest");
Finally, we have, at runtime, a value AEnum.TEST
(not with that direct call, but with Enum.valueOf
) with the label = labelTest.
Unfortunately, sun.reflect.*
classes are no longer available in OpenJDK11.
I've tried using jdk.internal.reflect.ConstructorAccessor
but I'm getting the error java: package jdk.internal.reflect does not exist
. And I don't think it's a good idea to rely on jdk.internal.*
classes.
Is there any OpenJDK11 alternative to create enums at runtime ?