zoukankan      html  css  js  c++  java
  • 利用Javassist获取Java类中的方法参数名、参数类型、方法访问类型

    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");
    			}
    		}
    	}
    }
  • 相关阅读:
    UVA 10391 STL容器的使用
    UVA 10763
    UVA 10935
    UVA 洪水
    UVA 1594 set 里面放queue
    关于STL 容器的嵌套使用, 小试牛刀
    丑数 UVA 136
    UVA 1368 DNA
    antd 上传文件控件使用方法(坑)
    mysql查询一条工单时间需要10秒。优化sql语句得以解决。
  • 原文地址:https://www.cnblogs.com/yangyh/p/2103576.html
Copyright © 2011-2022 走看看