javassist:增强型的java反射工具,获取方法参数名

java的反射是不能获取方法的参数名的。比如:

[java] view plaincopyprint?

  1. public String concatString(String str1,String str2){  

  2.     return str1+str2;  

  3. }  

    public String concatString(String str1,String str2){
        return str1+str2;
    }

想获取"str1",和"str1"这个参数名,使用JDK自带的反射是不行的。但是我们借助第三方包 javaassist 就可以获得。

[java] view plaincopyprint?

  1. public static void main(String[] args) {  

  2.     Class clazz = TestJavaAssist.class;  

  3.     try {  

  4.         ClassPool pool = ClassPool.getDefault();  

  5.         CtClass cc = pool.get(clazz.getName());  

  6.         CtMethod cm = cc.getDeclaredMethod("concatString");  

  7.   

  8.         // 使用javaassist的反射方法获取方法的参数名  

  9.         MethodInfo methodInfo = cm.getMethodInfo();  

  10.         CodeAttribute codeAttribute = methodInfo.getCodeAttribute();  

  11.         LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);  

  12.         if (attr == null) {  

  13.             // exception  

  14.         }  

  15.         String[] paramNames = new String[cm.getParameterTypes().length];  

  16.         int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;  

  17.         for (int i = 0; i < paramNames.length; i++)  

  18.             paramNames[i] = attr.variableName(i + pos);  

  19.         // paramNames即参数名  

  20.         for (int i = 0; i < paramNames.length; i++) {  

  21.             System.out.println(paramNames[i]);  

  22.         }  

  23.   

  24.     } catch (NotFoundException e) {  

  25.         e.printStackTrace();  

  26.     }  

  27. }  

public static void main(String[] args) {
		Class clazz = TestJavaAssist.class;
		try {
			ClassPool pool = ClassPool.getDefault();
			CtClass cc = pool.get(clazz.getName());
			CtMethod cm = cc.getDeclaredMethod("concatString");

			// 使用javaassist的反射方法获取方法的参数名
			MethodInfo methodInfo = cm.getMethodInfo();
			CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
			LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
			if (attr == null) {
				// exception
			}
			String[] paramNames = new String[cm.getParameterTypes().length];
			int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
			for (int i = 0; i < paramNames.length; i++)
				paramNames[i] = attr.variableName(i + pos);
			// paramNames即参数名
			for (int i = 0; i < paramNames.length; i++) {
				System.out.println(paramNames[i]);
			}

		} catch (NotFoundException e) {
			e.printStackTrace();
		}
	}

转载于:https://my.oschina.net/sniperLi/blog/492057

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值