2010-03-09 169 views

回答

15

下面是使用涉及基元的反射調用方法的一個簡單示例。

import java.lang.reflect.*; 

public class ReflectionExample { 
    public int test(int i) { 
     return i + 1; 
    } 
    public static void main(String args[]) throws Exception { 
     Method testMethod = ReflectionExample.class.getMethod("test", int.class); 
     int result = (Integer) testMethod.invoke(new ReflectionExample(), 100); 
     System.out.println(result); // 101 
    } 
} 

是穩健的,你應該捕獲並處理所有檢查反射有關的異常NoSuchMethodExceptionIllegalAccessExceptionInvocationTargetException

+0

@ polygenelubricants-thanks – Steven 2010-03-09 07:28:01

0

您可以在任何對象中使用getClass來發現其類。然後,您可以使用getMethods來發現所有可用的方法。一旦你有正確的方法,你可以調用invoke任意數量的參數

+0

顯示示例的任何鏈接 – Steven 2010-03-09 06:49:07

0

這是我所知道的最簡單的方法,它需要與包圍嘗試&陷阱:

方法M = .class.getDeclaredMethod( 「」,arg_1.class,arg_2.class,... arg_n.class); result =()m.invoke(null,(Object)arg_1,(Object)arg_2 ...(Object)arg_n);

這是爲了調用一個靜態方法,如果你想調用一個非靜態方法,你需要將m.invoke()的第一個參數從null替換爲調用底層方法的對象。

不要忘記添加一個導入到java.lang.reflect。*;

+0

如果我正在使用基元,該怎麼辦 – Steven 2010-03-09 07:02:03

+0

@Shuky:爲什麼將參數轉換爲Object? – 2010-03-09 08:48:56

+0

@Seteven,Carlos Heuberger:不需要投射,我的意思是他們不能是原始元素(而不是int,使用Integer等) – 2010-03-09 15:42:44

3

使用反射調用類方法非常簡單。 您需要創建一個類並在其中生成方法。如下所示。

package reflectionpackage; 

public class My { 
    public My() { 
    } 

    public void myReflectionMethod() { 
     System.out.println("My Reflection Method called"); 
    } 
} 

並使用反射在另一個類中調用此方法。

package reflectionpackage; 
import java.lang.reflect.InvocationTargetException; 
import java.lang.reflect.Method; 

public class ReflectionClass { 

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

Find more details here