一个Java反射机制例子
?來源:http://blog.csdn.net/loyoveui/archive/2007/06/22/1662154.aspx
?
package test;
import java.lang.reflect.Method;
public class InvokeTest {
? /**
?? *
?? * main 方法
?? * @param args
?? * void
?? */
? public static void main(String[] args) {
??? try {
????? InvokeTest invokeTest = new InvokeTest();
????? //1.第一步獲取方法的映射
????? //String[] realArgs = {"",""};//定義一個與execute方法第1個參數對應的String數組(注意此數組只為獲取方法的映射)
????? //Integer in = new Integer(0);//定義一個與execute方法第2個參數對應的Integer對象?????
????? //Class[] c_args = new Class[2];
????? //c_args[0] = realArgs.getClass();//分別獲取以上兩個參數的class
????? //c_args[1] = in.getClass();
????? //Method method = invokeTest.getClass().getMethod("execute", c_args);//返回值為test方法的映射(類型Method)
????? /**
?????? * 注意,以上幾句(11-16行)可以寫成下面一句
?????? * 目的是獲取execute方法的映射,第一個參數是方法,第二個參數是execute方法所需要的參數列表,類型是class
?????? * 所以當execute方法沒有參數時,getMethod第二個參數為null即可
?????? */
????? Method method = invokeTest.getClass().getMethod("execute",
????????? new Class[] { String[].class, Integer.class });
?????
????? //2.第二步調用方法
????? //String[] a1={"zhong","cheng"};//這里的數組用于做真正調用時的參數
????? //Integer a2=new Integer(5);//同上
????? //Object[] allArgs = new Object[2];
????? //allArgs[0] = a1;
????? //allArgs[1] = a2;
????? //Object[] result = (Object[])method.invoke(invokeTest, allArgs);//調用execute方法并獲取返回值
????? /**
?????? * 注意,以上幾句(21-26行)可以寫成下面一句
?????? * 目的是調用實例invokeTest的execute方法,參數(包含一個String數組和一個Integer對象)類型是Object
?????? * invoke()方法的第一個參數表示被調用的方法所屬類的實例,所以如果execute是靜態方法,
?????? * invoke的第一個參數可以為空
?????? */
????? Object[] result = (Object[])method.invoke(invokeTest, new Object[] {
????????? new String[] { "zhong", "cheng" }, new Integer(5) });
????? //打印出返回值
????? for(int i=0;i<result.length;i++){
??????? System.out.print(result[i]);
????? }
??? } catch (Exception e) {
????? e.printStackTrace();
??? }
? }
? /**
?? *
?? * 用于測試的execute方法,此處只是將String[]和Integer的值打印出來
?? * 并返回一個提示性的字符串數組
?? * @param String[] str
?? * @param Integer intN
?? * String[]
?? */
? public String[] execute(String[] str, Integer intN) {
??? for (int j = 0; j < str.length; j++) {
????? System.out.println(str[j]);
??? }
??? System.out.println(intN.intValue());
??? return new String[]{"display ","have ","bean ","finished "," !"};
? }
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的一个Java反射机制例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用CSS实现的模式窗口效果,弹出固定大小
- 下一篇: Java Application 直接通