• java 使用反射 实现指针


    简介

    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
    
    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    Qt:绘制时,用线性渐变填充一个圆角矩形范围
    记录一个mysql数据迁移的坑
    idea中添加jar,maven有时候无法引入到jar
    img引入base64格式图片
    URL特殊符号转码_encodeURI/decodeURI
    [js] eval函数
    Modernizr
    判断对象上是否存在指定key
    Linux下格式化大于2T硬盘的方法
    win10 别人无法ping通本机设置
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13408336.html
Copyright © 2020-2023  润新知