import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class InvokeMethod {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
Class<?> cls = Class.forName("java.lang.String");
// 通过反射访问静态方法
Method m = cls.getMethod("valueOf", char[].class);
char[] chars = {'l', 'o', 'v', 'e'};
Object res = m.invoke(null, chars);
System.out.println(res);
// 通过反射访问实例方法
Method m2 = cls.getMethod("startsWith", String.class);
// 通过反射访问构造方法
Object obj = cls.getConstructor(char[].class).newInstance(chars);
boolean res2 = (boolean) m2.invoke(obj, "l");
System.out.println(res2);
}
}
网友评论