mardi 25 août 2015

Invoke method dynamically with default values as parameters [duplicate]

This question already has an answer here:

I am trying to dynamically invoke some methods in a class using Java Reflection. Those methods have different amounts of parameters with varying types. Now, I am looking for an easy way to invoke them dynamically:

  • Primitive type parameters should use default value of primitive type as parameter value
  • Non-primitive type parameters should use NULL as parameter value

Here is what I have tried so far:

final List<Object> parameters = new ArrayList<Object>();
for (final Class<?> parameterType : method.getParameterTypes()) {
    if (parameterType.isPrimitive()) {

        // FIXME: use default value of primitive type
        final Class<?> nonPrimitiveClass = ClassUtils.primitiveToWrapper(parameterType);
        parameters.add(nonPrimitiveClass.newInstance());
    } else {
        parameters.add(null);
    }
}

final Screen currentScreen = (Screen) method.invoke(screenFactory, parameters.toArray());

Unfortunately my attempt to get the default value did not work as newInstance is trying to call the default constructor which is not existant for java.lang.Integer for example.

  1. Is there an easy way to get the primitive type default value without any external libraries except Apache lang?

  2. Is there another way to invoke methods dynamically with default parameters than my attempt?

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire