标题如何获得Method对象.
Method getMethod(String name,Class… parameterTypes.)//根据方法名和参数获得公共方法
Method[] getMethod();获得所有的公共方法
Method getDeclaredMethod(String name,Class…parameterTypes);根据方法名和参数获得方法(可以为非公共方法)
Method[] getDeclaredMethods();获得当前类中的所有方法。
标题Method的一些方法
String getName();获得方法名。
int getModifiers();获得修饰符。
Class getReturnTypes();获得返回值类型。
Class[] getParameterTypes();获得参数类型的数组。
Objec invoke(Object obj,Object…args);//执行方法
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = Math.class.getMethod("sqrt", double.class);//第二个参数如果是基本类型,不能用其包装类代替
double invoke = (Double)method.invoke(null,16D);//如果方法为static第一个参数为null或者用方法的类。如果为普通方法,则需为调用该方法的实例。
System.out.println("返回值:"+invoke);//输入4.0
System.out.println("方法名:"+method.getName());
System.out.println("返回值类型:"+method.getReturnType().getName());
System.out.println("参数列表"+Arrays.toString(method.getParameterTypes()));
System.out.println("修饰符:"+ Modifier.toString(method.getModifiers()));
}
返回值:4.0
方法名:sqrt
返回值类型:double
参数列表[double]
修饰符:public static