Java Scan Classpath Specify all Class__java under package path

Source: Internet
Author: User

In the writing framework often need to scan Classpath specified package path with a certain annotation class, their own packaging into a tool class, for your reference. Source Code

Classpathresourcescanner.java is as follows:

Package COM.BYTEBEATS.JUPITER.IOC;
Import Com.bytebeats.jupiter.util.ClassHelper;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;
Import Java.io.File;
Import java.io.IOException;
Import java.net.JarURLConnection;
Import Java.net.URL;
Import Java.net.URLDecoder;
Import java.util.*;
Import Java.util.jar.JarEntry;
Import Java.util.jar.JarFile;

Import Java.util.regex.Pattern; /** * ${description} * * @author Ricky Fung * @create 2016-12-11 16:02/public class Classpathcandidatecomponentsca

    Nner {private final Logger Logger = Loggerfactory.getlogger (GetClass ());

    public static final String Class_suffix = ". CLASS"; Private static final Pattern Inner_pattern = Java.util.regex.Pattern.compile ("\\$ (\\d+).",

    Java.util.regex.Pattern.CASE_INSENSITIVE); Public set<class<?>> findcandidatecomponents (String packagename) throws IOException {if (packagename. EndsWith (".")) {PackageName = packagename.substring (0, Packagename.length ()-1);
        map<string, string> classmap = new hashmap<> (32);
        String Path = Packagename.replace (".", "/");
        enumeration<url> urls = findallclasspathresources (path);
            while (Urls!=null && urls.hasmoreelements ()) {URL url = urls.nextelement ();
            String protocol = Url.getprotocol ();
                if ("File". Equals (protocol)) {String file = Urldecoder.decode (Url.getfile (), "UTF-8");
                File dir = new file (file);
                if (Dir.isdirectory ()) {Parseclassfile (dir, PackageName, Classmap);
                }else {throw new IllegalArgumentException ("File must be directory");
            else if ("jar". Equals (protocol)) {parsejarfile (URL, classmap);
        } set<class<?>> Set = new hashset<> (Classmap.size ());
           For (String Key:classMap.keySet ()) { String className = Classmap.get (key);
            try {set.add (Classhelper.forname (className));
            catch (ClassNotFoundException e) {e.printstacktrace ();
    } return set; } protected void Parseclassfile (File dir, String PackageName, map<string, string> classmap) {if (DIR.ISD
            Irectory ()) {file[] files = dir.listfiles ();
            for (file file:files) {parseclassfile (file, PackageName, Classmap);
            } else if (Dir.getname (). EndsWith (Class_suffix)) {String name = Dir.getpath ();
            Name = Name.substring (Name.indexof ("classes") +8). replace ("\", ".");
            System.out.println ("File:" +dir+ "\ T class:" +name);
        Addtoclassmap (name, Classmap);  } protected void parsejarfile (URL url, map<string, string> classmap) throws IOException {Jarfile Jar = ((jarurlconnection) url.openconnection()). Getjarfile ();
        enumeration<jarentry> entries = Jar.entries ();
            while (Entries.hasmoreelements ()) {Jarentry entry = entries.nextelement ();
            if (Entry.isdirectory ()) {continue;
            String name = Entry.getname ();
            if (Name.endswith (Class_suffix)) {Addtoclassmap (Name.replace ("/", "."), Classmap); }} Private Boolean Addtoclassmap (String name, map<string, string> classmap) {if (inner_p
            Attern.matcher (name). Find ()) {//filter out Anonymous inner class System.out.println ("Anonymous inner class:" +name);
        return false;
        } System.out.println ("Class:" +name);
        if (Name.indexof ("$") >0) {//Inner class SYSTEM.OUT.PRINTLN ("inner class:" +name);
        } if (!classmap.containskey (name)) {classmap.put (name, name.substring (0, Name.length ()-6));//Remove. class
    return true; } protected Enumeration<url> findallclasspathresources (String path) throws IOException {if (Path.startswith ("/")) {
        Path = path.substring (1);

        } enumeration<url> urls = Classhelper.getclassloader (). getresources (path);
    return URLs; }

}
How to use
Classpathcandidatecomponentscanner scanner = new Classpathcandidatecomponentscanner ();
The package name to be scanned
String packagename = "Com.bytebeats";
Gets the class name
set<class<?>> Set = scanner.findcandidatecomponents (PackageName) under the package;
System.out.println (Set.size ());
for (class<?> cls:set) {
    System.out.println (Cls.getname ());
}


There are already some good open source projects in this area, such as:
Reflections:https://github.com/ronmamo/reflections
scannotation:http://scannotation.sourceforge.net/

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.