mardi 8 septembre 2020

Reflection: invoke setter with Object or primitive value

I'm trying to invoke setter methods (method with 1 argument) with a supplied argument.

The argument matches the setter's argument signature except when it a primitive type because the value is passed down as an Object (autoboxed).

is there some way to cleanly unbox in case its a primitive?

i fear i might need something like so:

Object arg; // supplied from external code
Method method; // supplied externally as well
Class<?>[] parameterTypes = method.getParameterTypes();
Class<?> setterType = parameterTypes[0];
if (setterType.isPrimitive()) {
    if (setterType == boolean.class) {
        boolean bool = (boolean) arg;
        method.invoke(applyOn, bool);
    } else if (setterType == int.class) {
        //etc for all primitives
    }
} else {
    method.invoke(applyOn, arg);
}

but that seems ugly and still doesn't seem to work but still gives the exception:

java.lang.IllegalArgumentException: object is not an instance of declaring class
crm-tomcat               |  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
crm-tomcat               |  at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
crm-tomcat               |  at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
crm-tomcat               |  at java.base/java.lang.reflect.Method.invoke(Method.java:566)




Aucun commentaire:

Enregistrer un commentaire