zoukankan      html  css  js  c++  java
  • 4、java反射机制例子

    java反射机制例子:

    1.新建Calculator.java

    package invoke;

    public class Calculator {

        public int add(int a, int b) {

            return a + b;

        }

    }

    2.新建CalculatorTest.java,作为测试,采用反射机制获取到Calculator的add方法:

    package invoke;

    import java.lang.reflect.InvocationTargetException;

    import java.lang.reflect.Method;

    import invoke.Calculator;

    import org.junit.After;

    import org.junit.Before;

    import org.junit.Test;



    public class CalculatorTest {



        @Before

        public void setUp() throws Exception {

        }



        @After

        public void tearDown() throws Exception {

        }



        @Test

        public void testAdd() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

            //方法中所需要的参数

            Integer[] input = new Integer[]{new Integer(1), new Integer(2)};

            Class clazz = Class.forName("invoke.Calculator");

            //获取add方法的method

            @SuppressWarnings("unchecked")

            Method method = clazz.getMethod("add", new Class[]{int.class, int.class});

            Integer output = (Integer) method.invoke(new Calculator(), input);

            System.out.println("1 + 2 =" + output.intValue());

        }

    }

    3.运行结果:1 + 2 = 3





  • 相关阅读:
    SpringBoot多数据源:动态数据源
    cron 表达式
    6种@Transactional注解的失效场景
    spring boot 整合mybatis 的xml版本
    MySQL函数大全 及用法示例
    后端必备 Nginx 配置
    详解SpringBoot应用跨域访问解决方案
    Lombok使用
    前端必备 Nginx 配置
    随便写写插入排序
  • 原文地址:https://www.cnblogs.com/zmpandzmp/p/3648812.html
Copyright © 2011-2022 走看看