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");
    			}
    		}
    	}
    }
  • 相关阅读:
    [转]WIBKIT技术资料
    WebKit学习要点
    提高IOS开发效率的常用网站、开源类库及工具
    【浏览器那些基础】Android平台有那些CPU类型
    深刻的理解
    Spring Boot 最流行的 16 条实践解读,值得收藏!
    MyBatis动态SQL(认真看看, 以后写SQL就爽多了)
    为什么很多 SpringBoot 开发者放弃了 Tomcat,选择了 Undertow?
    朋友,别告诉我你懂分布式事务!
    分布式锁用 Redis 还是 Zookeeper?
  • 原文地址:https://www.cnblogs.com/yangyh/p/2103576.html
Copyright © 2011-2022 走看看