Java的反射機制-動態呼叫物件的方法
阿新 • • 發佈:2021-11-22
複製程式碼 package com.beidou.test; import java.lang.reflect.Method; public class Dynamic { public static void main(String[] args) throws Exception{ Class c = Dynamic.class;//得到物件 Method[] methods = c.getDeclaredMethods();//得到方法 for(Method method : methods){ System.out.print(method.getName());//列印引數名 Class[] parameterTypes = method.getParameterTypes(); for(int i=0;i<parameterTypes.length;i++){ String nameString=parameterTypes[i].getName(); System.out.print("parameterType:"+nameString);//列印方法引數型別 } System.out.print("ReturnType:"+method.getReturnType()); System.out.println(); } Object obj=c.newInstance();//獲取到方法物件,假設方法的引數是一個int,String,method名為getAge Method sAge = c.getMethod("getAge", new Class[] {int.class,String.class}); //獲得引數Object Object[] arguments = new Object[]{new Integer(23),new String("abc")}; //執行方法 String s=(String)sAge.invoke(obj , arguments); System.out.print(s); } public String getAge(int age,String name){ return name+": "+age; } }