I am trying to write a utility class that can take in a String
and Class<?>
and return back an Object
that is really the typed instance of that String
.
For example, if I have string "FALSE"
and class "java.lang.Boolean"
, I want to return the typed Boolean.FALSE
. Etc for other classes like String, Long, Int, Enum, etc.
I want to do this in a way that doesn't need too much re-writing when a new type is added. Currently I have a method with signature Object getTypedValue(Class<?> clazz, String value);
.
From here, I thought I could use a Map<Class<?>, Function<String, Object>>
. This works fine for cases like String and Boolean, but with the Enum case, I need the class name as well. So then the Map becomes Map<Class<?>, BiFunction<String, Class<?>, Object>>
.
But most of the methods do not need the Class parameter. Have also found that a new FunctionalInterface like:
@FunctionalInterface
public interface OptionalClassFunction<T, CLAZZ, R> {
R apply(T t, CLAZZ... clazz);
}
does not seem to work when I pass a method with only the T as the lambda.
e.g.
ImmutableMap.of(
Boolean.class, Util::toBoolean
)
private Boolean toBoolean(String value);
does not work.
Any suggestions on how to so something like:
Map<Class<?>, WhateverFunction<String, MAYBE_A_CLASS, Object>>
?
Example methods would be:
public static Boolean toBoolean(String value) {
// derive bool
}
public static Enum toEnum(String value, Class<?> fieldType) {
// derive enum
}
Aucun commentaire:
Enregistrer un commentaire