Gets all classes (scan file directory and all jars) that inherit or implement an interface under the specified package name

Source: Internet
Author: User

ImportJava.io.File;ImportJava.io.FileFilter;Importjava.io.IOException;Importjava.net.JarURLConnection;ImportJava.net.URL;ImportJava.net.URLDecoder;Importjava.util.Enumeration;ImportJava.util.Iterator;ImportJava.util.LinkedHashSet;ImportJava.util.Set;ImportJava.util.jar.JarEntry;ImportJava.util.jar.JarFile;/*** Created by Fanlinlong on 2017/4/13.*/ Public classItest { Public Static voidMain (string[] args) {//Package the following classset<class<?>> classes = getclasses ("Com.packge"); if(Classes = =NULL) {System.out.printf ("NULL"); } Else{System.out.printf (classes.size ()+ ""); //subclass of a class or interfaceset<class<?>> ininterface = Getbyinterface (Basebean.class, classes); System.out.printf (Ininterface.size ()+ ""); }    }    /*** Get all the class * * from the package@paramPack *@return     */     Public StaticSet<class<?>>getclasses (String pack) {//A collection of the first class classset<class<?>> classes =NewLinkedhashset<class<?>>(); //whether to loop iterations        Booleanrecursive =true; //get the name of the package and replace itString PackageName =pack; String Packagedirname= Packagename.replace ('. ', '/')); //defines a set of enumerations to be combined to loop through the things in this directoryEnumeration<url>dirs; Try{dirs=Thread.CurrentThread (). Getcontextclassloader (). Getresources (Packagedirname); //Loop Iteration down             while(Dirs.hasmoreelements ()) {//gets the next elementURL url =dirs.nextelement (); //get the name of the agreementString protocol =Url.getprotocol (); //if it is saved as a file on the server                if("File". Equals (protocol)) {System.err.println ("File type of Scan"); //get the physical path of the packageString FilePath = Urldecoder.decode (Url.getfile (), "UTF-8"); //scan files under the entire package in a file and add them to the collectionfindandaddclassesinpackagebyfile (PackageName, FilePath, recursive, Clas                SES); } Else if("Jar". Equals (protocol)) {                    //if it is a jar package file//Define a Jarfile//System.err.println ("Jar type Scan");jarfile jar; Try {                        //Get JarJar =( (Jarurlconnection) url.openconnection ()). Getjarfile (); //get an enumeration class from this jar packageenumeration<jarentry> entries =jar.entries (); //the same iteration of the loop                         while(Entries.hasmoreelements ()) {//get an entity in the jar can be a directory and some other files in the jar package such as meta-inf filesJarentry entry =entries.nextelement (); String name=Entry.getname (); //if it's A/start                            if(Name.charat (0) = = '/') {                                //gets the following stringName = name.substring (1); }                            //if the first part and the defined package name are the same                            if(Name.startswith (packagedirname)) {intIDX = Name.lastindexof ('/'); //If the end of the "/" is a package                                if(idx! =-1) {                                    //Get the package name replace "/" with "."PackageName = name.substring (0, IDX). Replace (‘/‘, ‘.‘); }                                //If you can iterate and be a package                                if(idx! =-1) | |recursive) {                                    //if it is a. class file and is not a directory                                    if(Name.endswith (". Class"))                                            &&!entry.isdirectory ()) {                                        //remove the ". Class" from the back to get the real class nameString ClassName =name.substring (packagename.length ()+ 1, name. Length ()+ P); Try {                                            //Add to ClassesClasses.add (Class. Forn Ame (PackageName+ '. ' +className)); } Catch(ClassNotFoundException e) {e.printstacktrace ();                        }                                    }                                }                            } }                    } Catch(IOException e) {//log.error ("Error getting file from Jar package while scanning user defined view");E.printstacktrace (); }                }            }        } Catch(IOException e) {e.printstacktrace (); }        returnclasses; }    /*** Get all the class * * under the package in the form of a file@paramPackageName *@paramPackagePath *@paramRecursive *@paramClasses*/     Public Static voidfindandaddclassesinpackagebyfile (String PackageName, String p Ackagepath,Final BooleanRecursive, set<class<?>>classes) {        //Gets the directory for this package to create a fileFile dir =NewFile (PackagePath); //If it does not exist or is not a directory, return directly        if(!dir.exists () | | |dir.isdirectory ()) {            //Log.warn ("User Defined package name" + PackageName + "without any files");            return; }        //if it exists, get all files under the package including directoryfile[] Dirfiles = Dir.listfiles (NewFileFilter () {//Custom Filter rules If you can loop (including subdirectories) or a file that ends in a. Class (Compiled Java class file)             Public BooleanAccept (file file) {return(Recursive &&file.isdirectory ())|| (File.getname (). EndsWith (". Class")));        }        }); //Loop All Files         for(File file:dirfiles) {//continue scanning if it is a directory            if(File.isdirectory ()) {Findandaddclassesinpackagebyfile (PackageName+ "." +file.getname (), File.getabsolutepath (), recursive, classes); } Else {                //If the Java class file is removed, the following. Class only leaves the class nameString className = File.getname (). substring (0, File.getname (). Length ()+ P); Try {                    //add to the collection//Classes.add (class.forname (PackageName + '. ' + className)); //after replying to the classmate's reminder, here with forname some bad, will trigger the static method, no use of ClassLoader load cleanClasses.add (Thread.CurrentThread (). Getcontextclassloader (). LoadClass (PackageName + '. ' +className)); } Catch(ClassNotFoundException e) {//log.error ("Add user Custom view class error cannot find this class of. class file");E.printstacktrace (); }            }        }    }    // --------------------------------------------------------------------------------------------------------@SuppressWarnings ({"Rawtypes", "unchecked"})     Public StaticSet<class<?>> Getbyinterface (Class clazz, set<class<?>>Classesall) {Set<Class<?>> classes =NewLinkedhashset<class<?>>(); //gets the implementation class for the specified interface        if(!Clazz.isinterface ()) {            Try {                /*** Loop to determine whether all classes under the path inherit the specified class * and exclude the parent class themselves*/Iterator<Class<?>> iterator =Classesall.iterator ();  while(Iterator.hasnext ()) {Class<?> CLS =Iterator.next (); /*** IsAssignableFrom The method, please refer to the blog: *http://blog.csdn.net/u010156024/article/details/44875195                     */                    if(Clazz.isassignablefrom (CLS)) {if(!clazz.equals (CLS)) {//not in itself .Classes.add (CLS); } Else {                        }                    }                }            } Catch(Exception e) {System.out.println ("Exception occurred"); }        }        returnclasses; }}

Gets all classes (scan file directory and all jars) that inherit or implement an interface under the specified package name

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.