调用任意方法-反射机制

       在C和C++中,可以从函数指针执行任意函数。从表明面上看,Java没有提供方法指针,即将一个方法的存储地址传给另外一个方法,以便第二个方法能够随后调用它。事实上,Java提供的接口(interface)是一种更好的解决方案。然而,反射机制允许你调用任意方法。

 

package methods;

import java.lang.reflect.Method;

public class MethodTableTest {
    /**
     * This program shows you how to invoke methods through reflection.
     */
    public static void main(String[] args) throws Exception {
        //get method pointer to the square and sqrt methods
        Method square = MethodTableTest.class.getMethod("square", double.class);
        Method sqrt = Math.class.getMethod("sqrt", double.class);

        //print tables of x- and y-values
        printTable(1, 10, 10, square);
        printTable(1, 10, 10, sqrt);
    }

    /**
     * Returns the square of a number.
     */
    public static double square(double x) {
        return x * x;
    }

    /**
     * Prints a table with x- and y-values for a method.
     */
    public static void printTable(double from, double to, int n, Method f) {
        //print out the method as table header
        System.out.println(f);

        double dx = (to - from) / (n - 1);

        for(double x = from; x <= to; x += dx) {
            try {
                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 methods.MethodTableTest.square(double)
    1.0000 |     1.0000
    2.0000 |     4.0000
    3.0000 |     9.0000
    4.0000 |    16.0000
    5.0000 |    25.0000
    6.0000 |    36.0000
    7.0000 |    49.0000
    8.0000 |    64.0000
    9.0000 |    81.0000
   10.0000 |   100.0000
public static double java.lang.Math.sqrt(double)
    1.0000 |     1.0000
    2.0000 |     1.4142
    3.0000 |     1.7321
    4.0000 |     2.0000
    5.0000 |     2.2361
    6.0000 |     2.4495
    7.0000 |     2.6458
    8.0000 |     2.8284
    9.0000 |     3.0000
   10.0000 |     3.1623

进程完成,退出码 0

猜你喜欢

转载自blog.csdn.net/m0_37732829/article/details/81869490
今日推荐