Package _02;import Java.io.file;import Java.net.url;public class Maintest_findallsubclass {public static void Main ( string[] Args) {class<?> clazz = maintest_findallsubclass.class;//navigate to the current package Path//url URL = Toy.class.getResource ("") ;//navigate to the bin directory url url = clazz.getresource ("/"); System.out.println (url); String fileName = Url.getfile (); System.out.println (fileName); String pathName = Filename.replacefirst ("/", "" "); System.out.println (pathName); File RootFile = new file (pathName), setsublist (rootfile, rootfile.getpath () + "\ \", clazz);} /** * Traverse all files in the bin directory * If the folder, then recursively add the files in the folder to the file array * If the file, load the file and force the type into the parent class to find the child class, the conversion no exception, the load class is the subclass of the parent class * (when traversing to the class itself, this is considered to be a subclass Of course this is my wishful thinking, I certainly do not tell you--〉 I am too troublesome. * But I still add the judgment--〉 self-requirement is Higher. *) * */public static <T> void setsublist (File rootfile, String parentdirectory,class<t> parentclass) {if (roo Tfile.isdirectory ()) {file[] files = rootfile.listfiles (); for (file file:files) {setsublist (file, parentdirectory, Pare ntclass);}} else {String className = null;try {if (rootFile.getpath (). indexOf (". class")! =-1) {className = rootfile.getpath (). replace (parentdirectory, ""). replace (". class "," "). replace (" \ \ ",". "); class<?> classobject = class.forname (className); classobject.assubclass (parentclass);//either A subclass or the class itself if (! Classname.equals (parentclass.getcanonicalname ())) {System.out.println (className + "extends" + parentclass);} Else{system.out.println (className + "is" + parentclass);}} Catch (classnotfoundexception e) {System.err.println ("can not find" + className);} Catch (classcastexception e) {System.err.println (className + "do not extends" + parentclass);}}} Test class Sub1 extends Maintest_findallsubclass {}//test class Sub2 extends Maintest_findallsubclass {}
Java finds all subclasses of a class