根据反射技术得到jar包中所有类,以及方法

来源:未知 责任编辑:责任编辑 发表时间:2013-08-27 16:00 点击:
函数背景:希望得到jar包中所有函数和包名,便于在客户端以树型结构展示
public static List<String[]> getJarMethod(String jarFile) throws Exception {
        String NORMAL_METHOD= "waitequalsnotifynotifyAlltoStringhashCodegetClass";
        List<String[]> a = new ArrayList<String[]>();
        try {
            //通过jarFile 和JarEntry得到所有的类
            JarFile jar = new JarFile(jarFile);//"D:/sip-test.jar"
            Enumeration e = jar.entries();
            while (e.hasMoreElements()) {
                JarEntry entry = (JarEntry) e.nextElement();
                //entry.getMethod()
                if (entry.getName().indexOf("META-INF") < 0) {
                    String sName = entry.getName();
                    String substr[] = sName.split("/");
                    String pName = "";
                    for (int i = 0; i < substr.length - 1; i++) {
                        if (i > 0)
                            pName = pName + "/" + substr[i];
                        else
                            pName = substr[i];
                    }
                    if (sName.indexOf(".class") < 0)
                    {
                        sName = sName.substring(0, sName.length() - 1);
                    }
                    else
                    {
                         //通过URLClassLoader.loadClass方法得到具体某个类
                        URL url1=new URL("file:D:\\sip-test.jar");
                        URLClassLoader myClassLoader=new URLClassLoader(new URL[]{url1},Thread.currentThread().getContextClassLoader());
                        String ppName = sName.replace("/", ".").replace(".class", "");
                        Class myClass = myClassLoader.loadClass(ppName);
                        //通过getMethods得到类中包含的方法
                        Method m[] = myClass.getMethods();
                        for(int i=0; i<m.length; i++)
                        {
                            String sm = m[i].getName();
                            if (NORMAL_METHOD.indexOf(sm) <0)
                            {
                                String[] c = {sm, sName};
                                a.add(c);
                            }
                        }
                    }
                    String[] b = { sName, pName };
                    a.add(b);
                }
            }
            return a;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return a;
    }
    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • Java编程语言的八大优点
    • JVM对象生命周期详细介绍
    • Java平台上的CRM系统
    • Java 算数测试小程序
    • Command(命令模式)
    • Java 一个简单的画图程序
    • Java环境 使用Resin在NT环境下配置JSP环境
    • Java 日历的小程序
    • Java 统计代码的小工具
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1