简体   繁体   中英

Generic method calling using java reflection api

I have been trying to develop an application. A bean script will be written as per requirement which in turn will call methods (defined in the application) in various order as per requirement. The application code (apart for bean script) would not be changed.

Also, the application uses external jars which provide large number of methods - of which some are implemented in the application. However, I would like to have the possibility to use the other methods (ones that are not yet implemented) without making changes to application should the requirement arise. For this, I would like to use the Java reflection API. The user should be able to call any method present in the external jars by passing the method name and corresponding parameters (using the the external jar documentation).

I'm a java newbie so I have some code that tries to achieve it (may not be syntactically correct):

public void callExternalJarMethod(String methodName, Class[] methodParameterTypes, Object[] methodParameters) 
throws NoSuchMethodException { 

String className = "SampleClassName"; 
Class classObject = Class.forName(className); 
Method methodObject;

    if (methodParameterTypes.length == 0) {
        methodObject = classObject.getMethod(methodName, null);
    } else {        
        methodObject = classObject.getMethod(methodName, methodParameterTypes);         
    } 

    // Not handling calling of static methods in which case "null" would be passed instead of methodObject to the invoke method
    Object returnValue = methodObject.invoke(methodObject, methodParameters);
}   

I'm trying to find a way I can get the Class[] methodParameterTypes, and Object[] methodParameters populated with the relevant values. I would have the parameter types and parameter values as string. Also, any pointers towards useful utils would be appreciated.

Thanks in advance.

You are not passing an instance of SampleClassName to the Method.invoke() call here...

Object returnValue = methodObject.invoke(methodObject, methodParameters);

If the method you are going to invoke is static , you can do this...

Object returnValue = methodObject.invoke(null, methodParameters);

Otherwise (non-static), you need to create an instance of SampleClassName to execute the method on.

If the class does not need any constructor arguments, you could use...

Object returnValue = methodObject.invoke(classObject.newInstance(), methodParameters);

(Obviously there will be a load of Exceptions that you need to handle by doing "newInstance" and "invoke"...)

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