0

I want to write a program which decides which methods to call on an object at runtime.

For example

 <method>getXyz<operation>
 <arg type="int"> 1 <arg>
 <arg type="float"> 1/0 <arg>

Now I have something like above in XML files and I want to decide which method to call at runtime. There can be multiple methods.

I don't want to do something like the following in my code:

 if (methodNam.equals("getXyz"))
     //call obj.getXyz()

How can I do it using Java reflection?

Also I want to construct the parameter list at runtime. For example, one method can take 2 parameters and another can take n arguments.

3 Answers 3

2

You should use Object.getClass() method to get the Class object first.

Then you should use Class.getMethod() and Class.getDeclaredMethod() to get the Method, and finally use Method.invoke() to invoke this method.

Example:

public class Tryout {
    public void foo(Integer x) { 
        System.out.println("foo " + x);
    }
    public static void main(String[] args) throws Exception {
        Tryout myObject = new Tryout();
        Class<?> cl = myObject.getClass();
        Method m = cl.getMethod("foo", Integer.class);
        m.invoke(myObject, 5);
    }
}

Also i want to construct the parameter list at runtime.For Example one method can take 2 parameters and other can take n args

This is not an issue, just create arrays of Class<?> for the types of the arguments, and an array of Objects of the values of the arguments, and pass them to getMethod() and invoke(). It works because these methods accept Class<?>... as argument, and an array fits it.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use the following code to a class method using reflection

package reflectionpackage;
public class My {
    public My() {
    }
   public void myReflectionMethod(){
        System.out.println("My Reflection Method called");
    }
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
        Class c=Class.forName("reflectionpackage.My");
        Method m=c.getDeclaredMethod("myReflectionMethod");
        Object t = c.newInstance();
        Object o= m.invoke(t);       
    }
}

this will work and for further reference please follow the link http://compilr.org/java/call-class-method-using-reflection/

Comments

-1

Have a good look at java.beans.Statement and java.beans.Expression. See here for further details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.