您的位置:首页 > 编程语言 > Java开发

使用java反射中的getMethod,invoke方法调用对象方法的实例

2012-08-01 11:03 1166 查看
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AsClass {
public X x;

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws InstantiationException,
ClassNotFoundException, SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
AsClass ac = new AsClass();
ac.x = new X();
String acName = ac.x.getClass().getSimpleName();

Class fake_x = Class.forName(acName);
Class[] newClass = new Class[1];
newClass[0] = String.class;

Method x_fun = fake_x.getMethod("show", newClass);
Object[] obj = new Object[1];
obj[0] = "Hello World";

x_fun.invoke(fake_x.newInstance(), obj);

}
}

class X {
public void show(String str) {
System.out.println(str);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: