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