I would like to write function which will invoke any method of any object in artificial way.
Code, I have already written:
Expand|Select|Wrap|Line Numbers
- import java.lang.reflect.Method;
- import java.lang.Class;
- import java.lang.reflect.Type;
- import static java.lang.System.out;
- class Calc
- {
- public long add(long a, long b) { return a + b; }
- }
- public class Main {
- public void manipulate (Object className, String methodName, String methodArg1, String methodArg2)
- {
- Class<?> c= className.getClass();
- Method mlist[] = c.getDeclaredMethods();
- for (Method m : mlist)
- {
- if (m.getName().equals(methodName))
- {
- Type[] paramTypes = m.getParameterTypes();
- Type returnType = m.getReturnType();
- m.setAccessible(true);
- Object ReturnValue = null;
- //out.format(returnType.toString(), ReturnValue);
- //out = m.invoke(className, ...);
- }
- }
- }
- public static void main(String[] args) {
- Main main = new Main();
- Calc c = new Calc();
- main.manipulate(c, "add", "2", "4");
- System.out.println("end");
- //System.out.println(c.add(-1,-2));
- }
- }
I have "2" and "4" (for example) as arguments. In paramTypes i have types, but i cannot initiate variables of those type.
I found in one solution Casting.ToType but it does not work.
Finally, I want to invoke method on object passed as parameter in method "manipulate".
I will be grateful for any idea. Thank You!
Paul