简体   繁体   中英

Passing values List as parameter a function

Im working on a Java class by using reflection, I have a list of different type of objects:

public List<Object> MethodSignatureObjects

and, I need to invoke a method by using the folowing logic:

   Class<?> c = Class.forName("class name");
   Method  method = c.getDeclaredMethod ("method name", parameterTypes)
   method.invoke (objectToInvokeOn, params)

Is there any way to put the objects contained on MethodSignatureObjects on getDeclaredMethod, I mean, something like this:

Method  method = c.getDeclaredMethod (methodName, param1.class, param2.class, ..); 

where parameters1 , parameters2, parameter n.... come from MethodSignatureObjects

I really appreaciate any advise.

Thank you so much.

You cant pass a list but an array to the method

// List<Object> methodSignatureObjects

int size = methodSignatureObjects.size();
Class<?>[] asArray = new Class<?>[size];
for ( int i = 0; i < size; i++ ) {
    asArray[i] = methodSignatureObjects.get(i).getClass();
}

Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", asArray);
method.invoke (objectToInvokeOn, params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM