0

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.

flogy
  • 906
  • 4
  • 16
  • If you write a method which returns the default value for a type, you can do this. A simple `Map` will do. – Peter Lawrey Aug 25 '15 at 15:27
  • 1
    I don't think there's a standard way to do it. you have to enumerate them yourself. – ZhongYu Aug 25 '15 at 15:29
  • I don't think this is a duplicate. I am asking for an easy way withoug using an external lib (as the answer in the other question was), and also I am asking for something else than just how to get default values, as this is only an attempt on how to achieve my goal, not the final solution. – flogy Aug 25 '15 at 15:30

0 Answers0