天天看點

javassist之取上級調用方法

private static Method getInvokingMethod(int index) {
    try {
        StackTraceElement stack[] = Thread.currentThread().getStackTrace();
        StackTraceElement parent = stack[index];
        Class cls = Class.forName(parent.getClassName());
        String methodName = parent.getMethodName();
        ClassPool pool = ClassPool.getDefault();
        ClassClassPath classPath = new ClassClassPath(cls);
        pool.insertClassPath(classPath);
        CtClass cc = pool.get(cls.getName());
        Class[] paramsTypes = null;
        for (CtMethod ctMethod : cc.getMethods()) {
            MethodInfo methodInfo = ctMethod.getMethodInfo();
            if (!methodName.equals(methodInfo.getName())) {
                continue;
            }
            //int ctMethodLine = methodInfo.getLineNumber(0);
            /* 取得方法起始行和結束行,然後對比執行的代碼是否在此方法區間内 */
            int ctMethodMaxLine = methodInfo.getLineNumber(Integer.MAX_VALUE);
            int ctMethodMinLine = methodInfo.getLineNumber();
            int methodLine = parent.getLineNumber();
            /* 探測StackTraceElement中所帶的行數是否超出了方法體外*/
            if(!(methodLine <= ctMethodMaxLine && methodLine >= ctMethodMinLine)){
                continue;
            }
            CtClass[] ctClass = ctMethod.getParameterTypes();
            paramsTypes = new Class[ctMethod.getParameterTypes().length];
            for (int i = ; i < ctClass.length; i++) {
                CtClass paramsType = ctClass[i];
                //CtPrimitiveType

                Class type = null;
                String clzzName = null;

                if(paramsType.isPrimitive()){
                    type = ClassUtils.forName(paramsType.getSimpleName(), Thread.currentThread().getContextClassLoader());
                }else{
                    type = ClassUtils.forName((paramsType.getPackageName()+"."+paramsType.getSimpleName()), Thread.currentThread().getContextClassLoader());
                }
                paramsTypes[i] = type;
            }
            break;
        }
        return ReflectionUtils.findMethod(cls,methodName,paramsTypes);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
/**
 * 取上層調用方法
 * @return
 */
public static Method getParentInvokingMethod() {
    return getInvokingMethod();
}

/**
 * 取得調用該方法的上層方法
 * @return
 */
public static Method getParentInvokingThisMethod() {
    return getInvokingMethod();
}
           

導包

import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import org.springframework.util.*;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;