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