package reflection;
import java.lang.reflect.*;
/**
* 利用反射调用方法
*/
public class MethodPointer {
public static void main(String[] args) throws Exception {
//先取得相应的方法:方法名称和该方法的参数
Method square = MethodPointer.class.getMethod("square", double.class);
Method sqrt = Math.class.getMethod("sqrt", double.class);
printTable(1, 10, 10, square);
printTable(1, 10, 10, sqrt);
}
private static void printTable(double from, double to, int n, Method f) {
System.out.println(f);
double dx = (to - from) / (n -1);
for(double x=from; x<=to; x+=dx) {
try {
//调用该方法:静态方法,第一个参数为null。否则传递一个对象。后面是该方法的参数
double y = (Double)f.invoke(null, x);
System.out.printf("%10.4f | %10.4f%n", x, y);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static double square(double x) {
return x * x;
}
}