简介

java 使用反射 实现指针,但不推荐使用,推荐使用 interface

code

package com;

import java.lang.reflect.*;

public class MethodTableTest {
	public static void main(String[] args) {
		Method square = null;
		try {
			square = MethodTableTest.class.getMethod("square", double.class);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Method sqrt = null;
		try {
			sqrt = Math.class.getMethod("sqrt", double.class);
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		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{
				double y = (Double) f.invoke(null, x);
				System.out.printf("%10.4f | %10.4f%n", x, y);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

Answer

public static double com.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
posted on 2020-07-31 10:39  HDU李少帅  阅读(244)  评论(0)    收藏  举报