Java-gets all the implementation classes that implement the specified interface class or inherits all subclasses of the specified class

Source: Internet
Author: User
Tags addall

During the actual programming process, we may encounter the problem of getting all the implementation classes that implement the specified interface class.
This tool class provides this functionality. The following is a detailed analysis of the tool class:

/** * Find all classes that implement the specified interface below the specified path * @author longyin * @author Blog Address: http://blog.csdn.net/u010156024 * If you have any questions or questions, please leave a message or comment, thank you!! */ Public  class classutil {    @SuppressWarnings({"Rawtypes","Unchecked"}) Public StaticArraylist<class>Getallclassbyinterface(Class clazz) {arraylist<class> list =NewArraylist<> ();//Determine if it is an interface        if(Clazz.isinterface ()) {Try{arraylist<class> Allclass = Getallclass (Clazz.getpackage (). GetName ());/** * Loop Determines whether all classes under the path implement the specified interface * and excludes the interface class itself * /                 for(inti =0; I < allclass.size (); i++) {/** * Judging is not the same interface * This method of parsing, please refer to the blog: * http://blog.csdn.net/u0 10156024/article/details/44875195 * *                    if(Clazz.isassignablefrom (Allclass.get (i))) {if(!clazz.equals (Allclass.get (i))) {//Does not add in itselfList.add (Allclass.get (i)); }Else{                        }                    }                }            }Catch(Exception e) {System.out.println ("Exception occurred"); }        }Else{//If the interface is not processed}returnList }/** * Find all classes from a specified path * @param name */    @SuppressWarnings("Rawtypes")Private StaticArraylist<class>Getallclass(String PackageName) {arraylist<class> list =NewArraylist<> ();        ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader (); String Path = Packagename.replace ('. ','/');Try{Arraylist<file> fileList =NewArraylist<> ();/** * This path uses a relative path * if you don't get it when you're testing, please clarify the path of the current project * Use relative path more stable!             * In addition, the path must not contain spaces, special characters and so on!             * I am in the test process due to the space, eat a big loss!!! */Enumeration<url> enumeration = Classloader.getresources (".. /bin/"+path); while(Enumeration.hasmoreelements ())                {URL url = enumeration.nextelement (); Filelist.add (NewFile (Url.getfile ())); } for(inti =0; I < filelist.size ();            i++) {List.addall (Findclass (Filelist.get (i), packagename)); }        }Catch(IOException e)        {E.printstacktrace (); }returnList }/** * If file is a folder, recursively call the Findclass method, or the class under the folder * If file itself is a class file, then join list to save and return * @param file *
     
       @param PackageName *
       @return *
      *    @SuppressWarnings("Rawtypes")Private StaticArraylist<class>Findclass(File file,string PackageName) {arraylist<class> list =NewArraylist<> ();if(!file.exists ()) {returnList } file[] files = file.listfiles (); for(File file2:files) {if(File2.isdirectory ()) {assert!file2.getname (). Contains (".");//Add assertions to determinearraylist<class> ArrayList = Findclass (File2, packagename+"."+file2.getname ());            List.addall (arrayList); }Else if(File2.getname (). EndsWith (". Class")){Try{//Saved class file does not require a suffix. classList.add (Class.forName (PackageName +'. '+ file2.getname (). SUBSTRING (0, File2.getname (). Length ()-6))); }Catch(ClassNotFoundException e)                {E.printstacktrace (); }            }        }returnList }}

The method above, you must remember to change the path when running the test. Must be updated with the relative path under the path where the current feature file is located, which is the executable. class file for the path execution.
The public method in the above class is provided to the outside to make the call, the method has a Isinterface judgment, add the judgment, you can only get all the classes that implement the specified interface, then to get inherited all classes of the specified class how to do it?
It is very simple, not to add this judgment.
All of the above public methods are changed as follows:

@SuppressWarnings({"Rawtypes","Unchecked"}) Public StaticArraylist<class>Getallclassbyinterface(Class clazz) {arraylist<class> list =NewArraylist<> ();//Gets the implementation class for the specified interface        if(Clazz.isinterface ()) {Try{arraylist<class> Allclass = Getallclass (Clazz.getpackage (). GetName ());/** * Loop Determines whether all classes under the path implement the specified interface * and excludes the interface class itself * /                 for(inti =0; I < allclass.size (); i++) {/** * Judging is not the same interface * IsAssignableFrom The method is parsed, please refer to the blog: */http blog.csdn.net/u010156024/article/details/44875195 * *                    if(Clazz.isassignablefrom (Allclass.get (i))) {if(!clazz.equals (Allclass.get (i))) {//Does not add in itselfList.add (Allclass.get (i)); }Else{                        }                    }                }            }Catch(Exception e) {System.out.println ("Exception occurred"); }//If it is not an interface, get all its subclasses}Else{Try{arraylist<class> Allclass = Getallclass (Clazz.getpackage (). GetName ());/** * Loop to determine whether all classes under the path inherit the specified class * and exclude the parent class themselves */                 for(inti =0; I < allclass.size (); i++) {/** * IsAssignableFrom The method, please refer to the blog: * http://blog.csdn.net/u010156024/article/ details/44875195 * *                    if(Clazz.isassignablefrom (Allclass.get (i))) {if(!clazz.equals (Allclass.get (i))) {//Does not add in itselfList.add (Allclass.get (i)); }Else{                        }                    }                }            }Catch(Exception e) {System.out.println ("Exception occurred"); }        }returnList }

In else, you can get all the subclasses that inherit the specified class!!!

I test complete, fully meet the needs!!!
If in doubt, please leave a message or comment!!

Java-gets all the implementation classes that implement the specified interface class or inherits all subclasses of the specified class

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.