简体   繁体   中英

Dynamically call method using reflection

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.

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 Object s 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.

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/

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

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