How to get method parameter names?

本文介绍了两种在Java中获取方法参数名称的方法:一是利用Javassist库解析字节码来提取参数名称;二是利用Java 8及以上版本提供的反射API直接获取参数名称,但需要在编译时启用-parameters选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何获取方法参数命名?

1.通过javassist获取

    /**
     * Get Method Parameter Names in JAVA
     * 参考:http://blog.hailinzeng.com/2014/10/10/get-method-parameter-name-in-java/
     *
     * @param clazz
     * @param method
     * @return 参数名称数组
     */
    public static String[] getMethodParamNames(Class<?> clazz, Method method) throws NotFoundException {
        ClassPool pool = ClassPool.getDefault();
        pool.insertClassPath(new ClassClassPath(clazz));
        CtClass cc = pool.get(clazz.getName());
        Class<?>[] paramTypes = method.getParameterTypes();
        String[] paramTypeNames = new String[method.getParameterTypes().length];
        for (int i = 0; i < paramTypes.length; i++)
            paramTypeNames[i] = paramTypes[i].getName();
        CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));

        MethodInfo methodInfo = cm.getMethodInfo();
        CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
        LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
                .getAttribute(LocalVariableAttribute.tag);
        if (attr == null) {
            throw new RuntimeException("class:" + clazz.getName()
                    + ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
        }

        String[] paramNames = new String[cm.getParameterTypes().length];
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int i = 0; i < attr.tableLength(); i++) {
            map.put(attr.index(i), i);
        }
        int index = 0;
        boolean isStaticMethod = Modifier.isStatic(cm.getModifiers());
        boolean flag = false;
        for (Integer key : map.keySet()) {
            //如果是非静态方法,第0个attr.variableName(0)返回this,所以要跳过
            if (!isStaticMethod && !flag) {
                flag = true;
                continue;
            }

            if (index < paramNames.length) {
                paramNames[index++] = attr.variableName(map.get(key));
            } else {
                break;
            }
        }
        return paramNames;
    }

参考:
Get Method Parameter Names in JAVA
How to get method parameter names with javassist?
Javassist初体验

2.java8 可直接使用java.lang.reflect.Parameter#getName()获取参数命名

前提是使用javac compiler,并在编译时带上-parameters option。具体参考
Obtaining Names of Method Parameters


### Spring AOP Execution Expression Usage and Examples In Spring AOP, the `execution` pointcut designator allows specifying which method executions should be matched based on patterns that describe methods' signatures. This powerful feature enables precise control over where aspects apply within an application. The general syntax for defining execution expressions follows this pattern: ```java execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) ``` For practical purposes, most developers focus primarily on matching return type (`ret-type-pattern`), package/class (`declaring-type-pattern`) and method names along with parameters (`name-pattern(param-pattern)`). #### Common Patterns Used in Execution Expressions - **Matching all public methods running anywhere**: ```java execution(public * *(..)) ``` - **Methods returning void from any class under com.example.service package**: ```java execution(void com.example.service.*.*(..)) ``` - **Specific Method Name Across All Classes Under Package** To match only specific named methods across classes inside a particular package hierarchy: ```java execution(* get*(..)) ``` This matches every method starting with "get" regardless of parameter count or types as long as it resides somewhere beneath the specified path. To demonstrate how these rules work together, consider creating an aspect logging entry/exit points around service layer operations using annotations like so[^1]: ```java @Aspect public class LoggingAspect { @Before("execution(* com.example.services..*.*(..))") public void logMethodEntry(JoinPoint joinPoint){ System.out.println("Entering:" + joinPoint.getSignature().getName()); } } ``` Here, whenever any method defined by services located directly under or nested within `com.example.services`, including subclasses, gets invoked—the associated message will print before proceeding further into actual business logic implementation details. --related questions-- 1. How does one define multiple pointcuts combining different criteria? 2. What differences exist between Before, After Returning, Around advices concerning their typical applications scenarios? 3. Can you provide more complex examples involving conditional weaving through custom annotations alongside standard ones provided out-of-the-box by Spring AOP framework? 4. In what situations might choosing XML configuration over annotation-based approach prove beneficial when working extensively with cross-cutting concerns management via AOP techniques offered by Spring ecosystem tools?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值