Today I learned that Spring uses a base package to scan all of the following classes, I think about how this is actually done, why spring is so magical, give a base package can get all the class name (including the child package) below it, the oneself ponder over, complete this function, also be to leave a little note to oneself , but also for those confusing programmers.
PS: These things are actually quite interesting, and sometimes think what seems to be very magical, when their own thinking clearly after the same.
Package test;
Import Java.io.File;
Import Java.net.URL;
Import Java.util.HashSet;
Import Java.util.Set;
The public class Classscan {/** * scans all classes (including child packages) under the given base package. * @param basepackagename The name of the base package * @return The full name of all classes under the base/public static set<string> Scanbasepackage (String Basepa
Ckagename) {String packagedirname = Basepackagename.replace (".", "/");
URL url = thread.currentthread (). Getcontextclassloader (). getresource (Packagedirname);
System.out.println (URL);
File TargetFile = new file (Url.getfile ());
if (!targetfile.exists () | | | targetfile.isfile ()) {throw new RuntimeException (Basepackagename + "is not a package name or the package name does not exist");
} set<string> classnames = new hashset<string> ();
Getallclass (TargetFile, Basepackagename, classnames);
return classnames; /** * Get all class file names in parentfile directory * @param parentfile * @param classnames * @param basepackagename/pri vate static void Getallclass (File parentfile, String basepackagename, set<string> clasSnames) {file[] files = parentfile.listfiles ();
for (File file:files) {String path = File.getpath (); if (File.isfile ()) {if (Path.endswith (". Class")) {Classnames.add (Basepackagename + "." + path.
SUBSTRING (path.lastindexof (' \ \) + 1, path.lastindexof ('. ')
)
);
}else{basepackagename = basepackagename + path.substring (path.lastindexof (' \ \ ') + 1);
Getallclass (file, Basepackagename, classnames);
}
}
}
}
Here are the test and run results:
public static void Main (string[] args) {
String basepackagename = "Cn.zq.spring.di.anotation";
set<string> classnames = Scanbasepackage (basepackagename);
System.out.println (classnames);
}
[Cn.zq.spring.di.anotationscan.PersonTest, Cn.zq.spring.di.anotationscan.Student, Cn.zq.spring.di.anotationscan.Person, Cn.zq.spring.di.anotation.PersonTest, Cn.zq.spring.di.anotation.Person]