mardi 2 juin 2015

is "emulation of inheritance" for generated classes justified use case for Reflection

Would the following use case be considered as justified for Reflection? I am getting bad looks and critics regarding my approach, with no concrete arguments other then it is reflection.

There are bunch of classes generated from XSDs (hundreds currently on project) which represent various Responses.

All of these Responses include common response data structure, rather then extending it.

When event such as timeout happens, i only need to set single String to specific value.

If these classes were extending common response structure i could always set this response code without reflection, but this is not the case.

Therefore i wrote simple utility for my services which uses reflection to get setter method for the String field and invoke it with predefined value. Only known alternative to me would be to have class specific methods which would duplicate code to handle timeout, with the only difference of returned Response class.

protected T handleTimeout(Class<T> timeoutClass) {
    try {
        T timeout = timeoutClass.newInstance();
        Method setCode = timeoutClass.getDeclaredMethod(SET_RESPONSE_CODE, String.class);
        setCode.invoke(timeout, Response.TIMEOUT.getCode());
        return timeout;
    } catch (InstantiationException | IllegalAccessException  | SecurityException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) {
        e.printStackTrace();
        throw new RuntimeException("Response classes must have field: \"code\" !");
    }

}

Relevant fact:

  • this setter method should never change as it would require rework of hundreds of interfaces

Could somebody point out if there are some pitfalls i have missed or if there is alternate solution for reflection which would achieve the same result ?





Aucun commentaire:

Enregistrer un commentaire