运行时在方法内部获取该方法的名称及参数相关信息

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;
    }
}

 

转载于:https://www.cnblogs.com/dongjak/p/4329258.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值