zoukankan      html  css  js  c++  java
  • 运行时在方法内部获取该方法的名称及参数相关信息

    package com.dongjak.scripts.java.反射;
    
    import java.lang.reflect.Method;
    
    import net.sf.json.JSONObject;
    
    import com.dongjak.annotations.LogTarget;
    
    /**
     * 
     * @author dongjak
     * 
     *
     */
    public class 运行时在方法内部获取该方法的名称及参数相关信息 {
        public static void main(String[] args) {
            test2("1");
    
        }
    
        public static void test1() {
    
            help();
        }
    
        public static void test2(@LogTarget(comment = "ff") String a) {
            help();
        }
    
        private static String help() {
            /*
             *  在运行时通过获取堆栈信息来提取当前方法所处的类路径及当前方法的名称
             */
            System.out.println(new JSONObject().fromObject(Thread.currentThread()
                    .getStackTrace()[2]));
            System.out
                    .println(Thread.currentThread().getStackTrace()[2].toString());
            System.out.println("--------------");
            String className = Thread.currentThread().getStackTrace()[2]
                    .getClassName();
            String methodName = Thread.currentThread().getStackTrace()[2]
                    .getMethodName();
            System.out.println(className);
            System.out.println(methodName);
    
            /*
             * 但在jvm装载该类的class文件时并不使用"形参"这个概念,形参只是在编码的时候方便程序员记忆的,因此无法通过原生的java api
             * 来获取运行时当前方法的形参名称(仅仅能够知道参数的个数),但可以借助参数注解来存储形参的名称或者其它相关信息,然后再通过
             * 反射来提取这些信息.不过这样感觉就不是那么完美了.
             */
            try {
                Class clazz = Class.forName(className);
                for (Method method : clazz.getMethods()) {
                    if (method.getName().equals(methodName)) {
                        System.out.println(method.getParameterAnnotations().length);
                        System.out.println(((LogTarget) method
                                .getParameterAnnotations()[0][0]).comment());
                        // System.out.println(this);
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return className;
        }
    }
  • 相关阅读:
    sql 自定义函数-16进制转10进制
    编写一个单独的Web Service for Delphi
    Web Service
    无需WEB服务器的WEBServices
    Svn总是提示输入账号密码
    阿里云服务器SQLSERVER 2019 远程服务器环境搭建
    svn客户端使用
    数据库设计规则(重新整理)
    数据库表字段命名规范
    怎样去掉DELPHI 10.3.3 启动后的 security alert 提示窗体
  • 原文地址:https://www.cnblogs.com/dongjak/p/4329258.html
Copyright © 2011-2022 走看看