zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Hello China最新开发进展
    虚拟软驱影像文件制作程序下载路径:http://download.csdn.net/source/738137
    Swing透明和变换
    利用Java存储过程简化数据库操作
    Hello China V1.5 源码下载地址
    防止程序重复执行的单元
    判断文件大小的函数
    TMainMenu 隐藏与显示菜单
    最简单的Delphi程序(控制台)
    测试代码
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/13408336.html
Copyright © 2011-2022 走看看