zoukankan      html  css  js  c++  java
  • 根据方法名称动态调用方法

    主要通过Java反射机制实现。

    例如:

    public class NewClass {
        private static final NewClass newClass = new NewClass();
        
        public  void doTest(String methodName){
            try {
                newClass.getClass().getMethod(methodName, new Class[]{}).invoke(newClass, new Object[]{});
            } catch (Exception ex) {
                Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        public void speak(){
            System.out.println("speak");
        }
        
        public void running(){
            System.out.println("running");
        }
        
    }
    public class Test {
        public static void main(String[] args) {
            NewClass newClass =  new NewClass();
            newClass.doTest("speak");
            newClass.doTest("running");
        }
    }

    运行结果:

    run:
    speak
    running
    成功构建 (总时间: 0 秒)
  • 相关阅读:
    二维数组排序
    php-快速排序
    sql优化相关
    全页面静态化缓存
    php--1-100相加之和
    php--阶乘
    socket
    posix_getpid 函数win下失效问题
    水仙花数
    常用的魔术方法
  • 原文地址:https://www.cnblogs.com/yshyee/p/4104870.html
Copyright © 2011-2022 走看看