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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
user978939
  • 131
  • 13

3 Answers3

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.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
amit
  • 175,853
  • 27
  • 231
  • 333
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/

sumit sharma
  • 1,067
  • 8
  • 24
-1

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

user207421
  • 305,947
  • 44
  • 307
  • 483