zoukankan      html  css  js  c++  java
  • java reflect反射调用方法invoke

    类定义

    package Reflect;
    
    public class MyTest {
        public int a;
        public static int b;
        public static final int c = 0;
        private int d;
    
        public int sum(int a, int b) {
            return a + b;
        }
    
        public int sub(int a, int b, String c) {
         System.out.println(c);
    return a - b; } MyTest() { } MyTest(int a, int b) { } }


    反射调用

    package Reflect;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    public class Test {
        public static void main(String[] args) {
            
            // invoke the reflect-method
            try {
                final Class z = Class.forName("Reflect.MyTest");
                final Class[] params = new Class[3];// define the param-type
                params[0] = int.class;
                params[1] = int.class;
                params[2] = String.class;
    
                // final Method m = z.getDeclaredMethod("sub", params);
                final Method m = z.getMethod("sub", int.class, int.class, String.class);
                // final Method m = z.getDeclaredMethod("sum", int.class, int.class);
    
                // set in-param
                final Object[] p = new Object[3];
                p[0] = 100;
                p[1] = 50;
                p[2] = "hello word!";
    
                System.out.println();
                final Integer s = (Integer) m.invoke(z.newInstance(), p);
                // final Integer s = (Integer) m.invoke(z.newInstance(), 3, 5);
                System.out.println("return value==" + s);
            } catch (final Exception e) {
                e.printStackTrace();
            }
    
        }
    }

    输出:

    hello word!
    return value==50

  • 相关阅读:
    LintCode Python 简单级题目 41.最大子数组
    helm深入学习
    kubernetes组件helm
    解压war包
    linux打开进程数测试
    docker使用centos7系统构建oraclejdk镜像
    docker使用centos7系统构建tomcat镜像
    docker使用alpine系统构建tomcat镜像
    docker制作共享jdk的tomcat镜像
    java cpu使用率高异常排查
  • 原文地址:https://www.cnblogs.com/pu20065226/p/10120297.html
Copyright © 2011-2022 走看看