JAVA中Method類invoke方法實例

package comm.test.invoke;

public class DemoA {
	public void hot(String str){ //打印傳入的字符串
		System.out.println(str); 
	}
}

package comm.test.invoke;

import java.lang.reflect.Method;

public class DoopRun {
	public static void main(String[] args){
		Class cls=DemoA.class;
		Object invokertester = null;
		try {
			invokertester = cls.newInstance();  //創建一個DemoA的對象,輸出“hello”這個字符串
			DemoA demoA=(DemoA)invokertester;
			demoA.hot("hello");
		} catch (Exception e) {
			e.printStackTrace();
		} 
		while(true){
			try{
				Method m = cls.getMethod("hot", new Class[]{String.class});
				//getMethod()方法的第一個參數爲要取得的對象名稱,後面爲參數類型的類
				m.invoke(invokertester, new Object[]{new String("world")});
				//第一參數爲表示要調用哪個對象的方法,第二個參數表示要向方法中傳入的參數
				Thread.sleep(1000);
				
			}catch(Exception e){
				
			}
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章