您的位置:首页 > 编程语言 > Java开发

利用Javassist获取Java类中的方法参数名、参数类型、方法访问类型

2013-02-18 01:03 696 查看
转载自:http://www.cnblogs.com/yangyh/archive/2011/07/12/2103576.html

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");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java javassist
相关文章推荐