2012-09-02 69 views
0

我想编写一个程序,它决定在运行时调用对象的方法。使用反射动态调用方法

例如

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

现在我已经在XML文件中类似上面,我想决定在运行时调用哪个方法。可以有多种方法。

我不想做这样的事情在我的代码如下:

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

我怎样才能做到这一点使用Java反射?

另外我想在运行时构造参数列表。例如,一种方法可以采用参数,另一种可以采用n参数。

回答

2

您应该首先使用Object.getClass()方法获取Class对象。

那么你应该使用Class.getMethod()Class.getDeclaredMethod()得到Method,最后使用Method.invoke()调用此方法。

实施例:

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); 
    } 
} 

此外,我希望构造参数列表在runtime.For实施例一个方法 可以采取2个参数和其它可以取n ARGS

这不是一个问题,只需创建阵列Class<?>对于类型的参数,以及一个数组Object s的参数值,并将它们传递给getMethod()invoke()。它可以工作,因为这些方法接受Class<?>...作为参数,并且一个数组适合它。

-1

请仔细看看java.beans.Statementjava.beans.Expression。进一步的细节见here

2

您可以使用下面的代码以类方法使用反射

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);  
    } 
} 

这会工作,并为进一步的参考,请按照链接 http://compilr.org/java/call-class-method-using-reflection/