1. 程式人生 > >java通過反射+javassist獲得方法所有資訊(返回值、方法名、引數型別列表、引數列表)

java通過反射+javassist獲得方法所有資訊(返回值、方法名、引數型別列表、引數列表)

眾所周知,使用java的反射無法獲得方法引數名列表,只能獲得方法引數型別列表,在網上研究了一下,發現有下面兩種方式實現:

方案一:使用反射+javassit庫

static void javassistGetInfo() throws Exception{
		 Class<?> clazz = Class.forName("fanshe.Person");
		 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++;
					}
				}
		 }
		 
	}

方案二:使用spring的LocalVariableTableParameterNameDiscoverer,相比於javassit,這種方式要簡單太多,所以推薦使用這種
import java.lang.reflect.Method;  
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;  
  
public class GetParamNames {  
    public static void main(String[] args) {  
        LocalVariableTableParameterNameDiscoverer u =   
            new LocalVariableTableParameterNameDiscoverer();  
        Demo demo = new Demo();  
        Method[] methods = demo.getClass().getDeclaredMethods();  
        String[] params = u.getParameterNames(methods[0]);  
        for (int i = 0; i < params.length; i++) {  
            System.out.println(params[i]);  
        }  
    }  
}