利用Javassist擷取Java類中的方法參數名、參數類型、方法訪問類型

來源:互聯網
上載者:User
http://www.csg.is.titech.ac.jp/~chiba/javassist/
package com.vl;import java.lang.reflect.Method;import javassist.ClassPool;import javassist.CtClass;import javassist.CtMethod;import javassist.Modifier;import javassist.NotFoundException;import javassist.bytecode.AccessFlag;import javassist.bytecode.CodeAttribute;import javassist.bytecode.LocalVariableAttribute;import javassist.bytecode.MethodInfo;import com.vl.app.PTZ;import com.vl.app.StreamsUtil;import com.vl.sql.UserDAO;public class VLInterface {public static void main(String[] args) throws NotFoundException {ClassPool pool = ClassPool.getDefault();Class[] cs = new Class[] { PTZ.class, UserDAO.class ,StreamsUtil.class};String[] prefixStrings = new String[] { "ptz", "user" ,"streamsutil"};for (int i = 0; i < cs.length; i++) {CtClass ctClass;Class clz = cs[i];ctClass = pool.get(clz.getName());Method[] methods = clz.getDeclaredMethods();for (Method m : methods) {String name = m.getName();CtMethod cm = ctClass.getDeclaredMethod(name);MethodInfo methodInfo = cm.getMethodInfo();Class[] parameterTypes = m.getParameterTypes();CodeAttribute codeAttribute = methodInfo.getCodeAttribute();LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);if (attr == null) {// exception}if(cm.getMethodInfo().getAccessFlags()!=AccessFlag.PUBLIC)continue;//System.out.println();String[] paramNames = new String[cm.getParameterTypes().length];int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;for (int j = 0; j < paramNames.length; j++)paramNames[j] = attr.variableName(j + pos);// paramNames即參數名System.out.printf("\"%s.%s\":\r\n\tReturn:%s\t(Parameters ",prefixStrings[i], name, m.getReturnType().getSimpleName());for (int i1 = 0; i1 < paramNames.length; i1++) {System.out.printf("%d:[%s %s] ", i1+1, parameterTypes[i1].getSimpleName(), paramNames[i1]);}// for (Class class1 : parameterTypes) {// System.out.printf("[%s],", class1.getName());// }System.out.println(")\r\n");}}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.