Java核心技术卷 反射
反射最后的一个知识点
代码实例
package reflection.methods;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodTableT {
public static void main(String[] args) throws NoSuchMethodException {
Method square = MethodTableT.class.getMethod("square", double.class);
// Method sqrt = Math.class.getMethod("sqrt" , double.class);
Class c1 = Class.forName("java.lang.Math");
Method sqrt = c1.getMethod("sqrt" , double.class);
printTable(1,10,10,square);
printTable(1,10,10,sqrt);
}
public static double square(double x){
return x*x;
}
public 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 {
// invoke(implicitParameter,explicitParameter) 静态方法 第一个参数可忽略将其设置为null
// invoke的参数返回值类型必须是Object类型
double y = (double) f.invoke(null , x);//f 代表 square方法
System.out.printf("%10.4f | %10.4f%n", x , y); // printf格式转换 println print 区别
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
调用任意方法
自定义方法square f.invoke()
Java中Math.sqrt()