public class A { public void a() {} public void a(String x) {} public static String x() {return "x";} } Class clazz = A.class; //new A().getClass(); both OK! A aObj = new A(); Method methodA = clazz.getMethod("a", null); //clazz.getMethod("a", new Class[] {}); both OK! methodA.invoke(aObj, null); //or (aObj, new Class[] {}); Method methodAX = clazz.getMethod("a", new Class[] {String.class}); methodAX.invoke(aObj , new Object[] {"x"}); //aObj.a("x"); Method methodX = clazz.getMethod("x", null); String s = (String)methodX.invoke(null, null);
invoke调用.详细的自己看API文档,很简单.
public void a() {}
public void a(String x) {}
public static String x() {return "x";}
}
Class clazz = A.class; //new A().getClass(); both OK!
A aObj = new A();
Method methodA = clazz.getMethod("a", null); //clazz.getMethod("a", new Class[] {}); both OK!
methodA.invoke(aObj, null); //or (aObj, new Class[] {});
Method methodAX = clazz.getMethod("a", new Class[] {String.class});
methodAX.invoke(aObj , new Object[] {"x"}); //aObj.a("x");
Method methodX = clazz.getMethod("x", null);
String s = (String)methodX.invoke(null, null);