鍍金池/ 問答/Java/ 如何在方法內(nèi)部獲取當前方法的參數(shù)列表的類類型

如何在方法內(nèi)部獲取當前方法的參數(shù)列表的類類型

如何在方法內(nèi)部獲取當前方法的參數(shù)列表的類類型
在方法內(nèi)部實現(xiàn)與method.getParameterTypes();相同的效果;

回答
編輯回答
壞脾滊

提個思路:

final String methodName = new Exception().getStackTrace()[0].getMethodName();

然后反射拿到這個方法對應的 Method 實例。

2017年6月29日 14:49
編輯回答
紓惘
public class Common{
    // 獲取某方法的參數(shù)類型數(shù)組
    public Class[] getParameterTypes(){
        return this.getParameterTypes(1);
    }
    public Class[] getParameterTypes(int i){
        StackTraceElement stackTraceElement = new Throwable().getStackTrace()[i];
        try {
            Method[] ms = Class.forName(stackTraceElement.getClassName()).getMethods();
            for (Method m : ms) {
                if (m.getName().equals(stackTraceElement.getMethodName())) {
                    return m.getParameterTypes();
                }
            }
        }catch (ClassNotFoundException ex){}
        return new Class[0];
    }
}

有問題或有更簡便的方法請指出,謝謝;

2018年1月26日 02:19