What I am trying to build is a list of enum classes that have got more advanced valueOf methods. Since that method cannot be overwritten and therefore extended, I have thought to make a class holding all enumerations which have advancedValueOf methods and run it by lambda. The problem I am facing is that registration of the enum is in static{} code, which is triggered AFTER the enum is checked for the first time.
public enum SimpleEnum
{
ONE,
TWO;
static
{
EnumTest.registerEnum(SimpleEnum.class, SimpleEnum::advancedValueOf);
}
public static SimpleEnum advancedValueOf(String s)
{
return ONE;//This method would find enum by its parameters
}
}
//------------------------------------------------
public class EnumTest
{
private static final Map<Class<?>, Function<String, ?>> _advancedValueOfEnums = new HashMap<>();
public static void main(String[] args)
{
getValue(SimpleEnum.class, "1");
}
public static <T extends Enum<T>> void registerEnum(Class<T> enumClass, Function<String, T> advancedValueOf)
{
_advancedValueOfEnums.put(enumClass, advancedValueOf);
}
public static void getValue(Class<?> enumClass, String value)
{
System.out.println("Contains=" + _advancedValueOfEnums.containsKey(enumClass));
}
}
Message printed to the console is "Contains=false". What can I do to make it "Contains=true"?
This answer: Why can't enum's constructor access static fields? shows what is wrong with accessing static field from enum constructor, I am asking about accessing static value of enum from a different class which should have already been initialized.