Java通過反射調用方法
下面代碼演示如何通過反射調用方法。
首先通過Class實例的getDeclaredMethods()獲得所有方法的定義,然后通過Method的invoke方法觸發方法調用,invoke方法的第一個參數是方法所屬對象,第二個參數是方法調用的參數列表。
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;public class Main {
/** * Invokes the methods of an object using the Reflection api. */ public void invokeMethodsUsingReflection() { //Obtain the Class instance Class computerClass = Computer.class; //Get the methods Method[] methods = computerClass.getDeclaredMethods(); //Create the object that we want to invoke the methods on Computer computer = new Computer(); //Loop through the methods and invoke them for (Method method : methods) { Object result; try { //Call the method. Since none of them takes arguments we just //pass an empty array as second parameter. result = method.invoke(computer, new Object[0]); } catch (IllegalArgumentException ex) { ex.printStackTrace(); return; } catch (InvocationTargetException ex) { ex.printStackTrace(); return; } catch (IllegalAccessException ex) { ex.printStackTrace(); return; } System.out.println(method.getName() + ": " + result); } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().invokeMethodsUsingReflection(); } class Computer { private String brand = "DELL"; private String type = "Laptop"; private int harddiskSize_GB = 300; private boolean AntiVirusInstalled = true; public String getBrand() { return brand; } public String getType() { return type; } public int getHarddiskSize_GB() { return harddiskSize_GB; } public boolean isAntiVirusInstalled() { return AntiVirusInstalled; } }
}</pre>
本文由用戶 lplo 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!