Java traversal of all classes under the specified package name (support Jar)

Source: Internet
Author: User
Tags addall

package com.shdl.htscada.utils;import java.io.file;import java.io.ioexception;import  Java.io.unsupportedencodingexception;import java.net.jarurlconnection;import java.net.url;import  java.net.URLClassLoader;import java.util.Enumeration;import java.util.HashSet;import  java.util.set;import java.util.jar.jarentry;import java.util.jar.jarfile;/** *  traversal of all classes under the specified package name (Support jar)  *  @author  ht-meeting *  @date  2017 July 7  */public class  Classfilesutils {public static void main (String[] args)  throws Exception  {String packageName =  "com.shdl.htscada.i18n"; Set<string> classnames = getclassname (packagename, false,  ". Properties");   (Classnames != null)  {for  (string classname : classnames)  { System.out.println (ClassName);}}} /** *  get all Classes  *  @param under a package  p ackagename  Package Name  *  @param  isRecursion  whether to traverse a child package  *  @param  suffixstr  After able name  *  @return   Full Name of Class  */public static set<string> getclassname (String &NBSP;PACKAGENAME,&NBSP;BOOLEAN&NBSP;ISRECURSION&NBSP;,STRING&NBSP;SUFFIXSTR)  {Set<String>  classnames = null; Classloader loader = thread.currentthread (). Getcontextclassloader (); String packagepath = packagename.replace (".",  "/"); Url url = loader.getresource (PackagePath);if  (url != null)  {String  Protocol = url.getprotocol ();if  (protocol.equals ("file"))  {classNames =  Getclassnamefromdir (Url.getpath (),  packagename, isrecursion, suffixstr);}  else if  (Protocol.equals ("jar"))  {JarFile jarFile = null;try{                 jarfile =  ((jarurlconnection)  url.openconnection ()). Getjarfile ();  catch (exception e) {e.printstacktrace ();} if (jarfile != null) {Getclassnamefromjar (Jarfile.entries (),  packagename, isrecursion);}}}  else {/* finds the package name */classnames = getclassnamefromjars (((urlclassloader) loader) from all jar packages. getURLs (),  packagename, isrecursion);} Return classnames;} /** *  All Classes  *  @param  filePath  file Paths  *  @param  classname from the project file for a package   Class name Collection  *  @param  isRecursion  whether to traverse a child package  *  @param  suffixstr  able name  *   @return   class full name  */private static set<string> getclassnamefromdir (String &NBSP;FILEPATH,&NBSP;STRING&NBSP;PACKAGENAME,&NBSP;BOOLEAN&NBSP;ISRECURSION,&NBSP;STRING&NBSP;SUFFIXSTR)   {set<string> classname = new hashset<string> ();try {filePath =  Java.net.URLDecoder.decode (New string (FilepAth.getbytes ("iso-8859-1"),  "UTF-8"),  "UTF-8"); File file = new file (FilePath); File[] files = file.listfiles ();for  (file childfile : files)  {if  (Childfile.isdirectory ())  {if  (isrecursion)  {classname.addall (Getclassnamefromdir ( Childfile.getpath (),  packagename+ "." +childfile.getname (),  isrecursion, suffixstr));}}  else {string filename = childfile.getname (;if ) (FileName.endsWith (SUFFIXSTR)  && !filename.contains ("$"))  {//classname.add (fileName); Classname.add (packageName+   "."  + filename);}}}  catch  (unsupportedencodingexception e)  {e.printstacktrace ();} Return classname;} /** *  @param  jarEntries *  @param  packageName *  @param  isrecursion  *  @return  */private static set<string> getclassnamefromjar (Enumeration <jarentry>  jarentries, string packagename, boolean isrecursion) {Set<String>  Classnames = new hashset<string> ();while  (Jarentries.hasmoreelements ())  { Jarentry jarentry = jarentries.nextelement (); if (!jarentry.isdirectory ()) {/*              *  here is for convenience, first turn "/"   turn   "."   Re-judgment   ". Class"   practice may be bug              *  (fixme:  First "/"   turn   "."   Re-judgment   ". Class"   practice may have bugs)               */string entryname = jarentry.getname (). Replace ("/",  "."); if  (Entryname.endswith (". Class")  && !entryname.contains ("$")  &&  Entryname.startswith (PackageName))  {entryname = entryname.replace (". Class",  ""); if ( Isrecursion) {CLASSNAMES.ADD (entryName);}  else if (!entryname.replace (packagename+ "",  ""). Contains (".")) {Classnames.add (entryName);}}}} Return classnames;} /** *  search for the package from all jars and get all classes  *  @param  urls url collections under the package  *  @param   packagename  package Path  *  @param  isRecursion  whether to traverse the child package  *  @return   The full name of the class  */ Private static set<string> getclassnamefromjars (url[] urls, string  Packagename, boolean isrecursion)  {Set<String> classNames = new  Hashset<string> ();for  (int i = 0; i < urls.length; i++)   {String classpath = urls[i].getpath ();//Do not search Classes folder if  (Classpath.endswith ("classes/"))  {continue;} Jarfile jarfile = null;try {jarfile = new jarfile (ClassPath.substring ( Classpath.indexof ("/")));}  catch  (ioexception e)  {e.printstacktrace ();} If  (Jarfile != null)  {classnames.addall (Getclassnamefromjar (jarfile.entries (),  packagename, isrecursion));}} Return classnames;}}


Java traversal of all classes under the specified package name (support Jar)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.