javaweb icon indicating copy to clipboard operation
javaweb copied to clipboard

获取方法参数名

Open www1350 opened this issue 7 years ago • 0 comments

通过spring的asm

Method[] methods = CarServiceImpl.class.getMethods();
        LocalVariableTableParameterNameDiscoverer local=new LocalVariableTableParameterNameDiscoverer();
        String[] params=local.getParameterNames( methods[0]);
        for(String param: params){
            System.out.println(param);
        }

通过javassist

        Class<?> clazz = Class.forName("com.absurd.rick.service.impl.CarServiceImpl");
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get(clazz.getName());

        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method mt:declaredMethods) {
            String modifier = Modifier.toString(mt.getModifiers());
            Class<?> returnType = mt.getReturnType();
            String name = mt.getName();
            Class<?>[] parameterTypes = mt.getParameterTypes();

            System.out.print("\n"+modifier+" "+returnType.getName()+" "+name+" (");


            //CtMethod[] declaredMethods1 = cc.getDeclaredMethods();
            CtMethod ctm = cc.getDeclaredMethod(name);
            MethodInfo methodInfo = ctm.getMethodInfo();
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
            LocalVariableAttribute attribute = (LocalVariableAttribute)codeAttribute.getAttribute(LocalVariableAttribute.tag);
            int pos = Modifier.isStatic(ctm.getModifiers()) ? 0 : 1;
            for (int i=0;i<ctm.getParameterTypes().length;i++) {
                System.out.print(parameterTypes[i]+" "+attribute.variableName(i+pos));
                if (i<ctm.getParameterTypes().length-1) {
                    System.out.print(",");
                }
            }

            System.out.print(")");

            Class<?>[] exceptionTypes = mt.getExceptionTypes();
            if (exceptionTypes.length>0) {
                System.out.print(" throws ");
                int j=0;
                for (Class<?> cl:exceptionTypes) {
                    System.out.print(cl.getName());
                    if (j<exceptionTypes.length-1) {
                        System.out.print(",");
                    }
                    j++;
                }
            }
        }

www1350 avatar Aug 29 '17 08:08 www1350