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


2009-05-19 18:36:00

http://linkyou.blog.51cto.com/1332494/283242


函数背景:希望得到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; 
  
     }


http://linkyou.blog.51cto.com/1332494/283242