vendredi 1 septembre 2017

Java enum anonymous inner class and reflection

I have an enum with anonymous inner class like:

public enum Status {

    PRELIMINARY() {
    @Override
    boolean process() {
        return true;
    }

    SUBMITTED() {
    @Override
    boolean process() {
        return false;
    }

    abstract boolean process();

}

I need to use reflection to set a field on a model like:

private static void setFieldValue(T instance, Class<?> klazz, String setterName, Object value) {
    Method method = klazz.getDeclaredMethod(setterName, value.getClass());
    method.invoke(instance, value);
}

This works great for most of the model fields, except it does not work for my Status class, where it will throw a NoSuchMethodException. This is because the class of my value will be package.Status$1 instead of package.Status.

Is there a good work around for this?





Aucun commentaire:

Enregistrer un commentaire