Java Scan Package

Source: Internet
Author: User

In Java, there is often a need to "scan a package and then find the full class", and spring supports it directly,

Reflections This toolkit is also good, MAVEN relies on the following:

(I have introduced the Hessian service before)

<dependency>    <groupId>org.reflections</groupId>    <artifactid>reflections</ Artifactid>    <version>0.9.10</version></dependency>
Java Scan Package

Because it is the lower level of things, although the code can be implemented, but it is a very cumbersome and difficult to solve the problem;

The following code, scanning their own code is absolutely no problem, scanning other people's code premise, you must ensure that the code is not blind,. class file determines that can be converted to a class object;

(as a learning and communication bar, the improvement Program is to verify the. class file, and then convert the. class file to a class object, if you are interested in perfecting it, I have abandoned the pit).

ImportJava.io.ByteArrayOutputStream;ImportJava.io.File;ImportJava.io.FileFilter;ImportJava.io.FileInputStream;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.Channels;ImportJava.nio.channels.FileChannel;ImportJava.nio.channels.WritableByteChannel;Importjava.util.ArrayList;Importjava.util.List;ImportCom.sea.common.util.Resource;ImportCom.sea.common.util.StrStream;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;/*** Compile any class file, you need to ensure that the class file is available, otherwise error * *@authorChenss August 25, 2017 morning 10:04:38 **/@Deprecated Public classMyclassloaderextendsclassloader{Private StaticLogger Logger = Loggerfactory.getlogger (ClassLoader.class);  PublicMyclassloader () {Super(Resource.getclassloader ()); }         Public Static voidMain (string[] args)throwsclassnotfoundexception {myclassloader loader=NewMyclassloader (); Try{List<Class<?>> clazz = loader.load ("c:/users/chenss/desktop/Code Test/build/classes/", "Com.css.common.util");        System.out.println (Clazz); } Catch(Exception e) {e.printstacktrace (); }    }     PublicList<class<?>>Load (string location, string pkg) {returnLoadNewFile (location), pkg); }     PublicList<class<?>>Load (file file, String pkg) {//Strstream is a custom string validation tool that looks for files with a pkg (package name) and no dollar symbolStrstream stream =NewStrstream (). prefix (pkg). Notexists (' $ ')); returnload (file, stream); }     PublicList<class<?>>Load (file file, Strstream stream) {List<Class<?>> classes =NewArraylist<>(); if(File.exists () &&file.isdirectory ()) {             for(File Dir:likefile (file, "", Stream)) {                if(Dir.isdirectory ()) {Traversefile (dir, Dir.getname (), classes, stream); } Else {                    //the root directory class                }            }        }        returnclasses; }    /*** Search All files recursively, find all. class Files *@paramdir *@paramPkg *@paramClasses *@paramStream*/      Public voidTraversefile (File dir, String pkg, list<class<?>>classes, Strstream stream) {         for(File file:likefile (dir, pkg, stream)) {if(File.isdirectory ()) {//folders traverse the next level of directoryTraversefile (file, pkg + '. ' +File.getname (), classes, stream); } Else {                //generate class<?> directly based on the. class fileString ClassName =NULL; Try{String FileName=File.getname (); ClassName= pkg + '. ' + filename.substring (0, Filename.length ()-6); Class<?> Clazz =format (file, className);                    Logger.debug (Clazz.tostring ());                Classes.add (Clazz); } Catch(Exception e) {e.printstacktrace (); Logger.error (ClassName+ ": Load Error"); Continue; }            }        }    }     Publicclass<?> Format (string fileName, String className)throwsException {returnFormatNewFile (fileName), className); }    /*** Generate Class<?> directly from the. class file, from Io to object conversion, Io is not checked;     * Therefore, if you want to use this class, you must ensure that all the. class files can create Java classes; * Manual encoding, and compilation of the passed. class file will not be problematic;     * When scanning your unfamiliar. class file, if the contents of the. class file are incorrect, it is possible to generate an error that forces the main function to break. */     Publicclass<?> format (file file, String className)throwsException {fileinputstream fis=Newfileinputstream (file); FileChannel Filec=Fis.getchannel (); Bytearrayoutputstream BAOs=NewBytearrayoutputstream (); Writablebytechannel WBC=Channels.newchannel (BAOs); Bytebuffer Buffer= Bytebuffer.allocatedirect (1024);  while(Filec.read (buffer) > 0) {buffer.flip ();            Wbc.write (buffer);        Buffer.clear (); }        byte[] B =Baos.tobytearray ();        ioutils.closequietly (BAOs, WBC, Filec, FIS); returnDefineClass (ClassName, B, 0, b.length); }    /**     *      * @paramDir folder *@paramstring path name *@paramStream string Check class *@return     */     Public Staticfile[] Likefile (File dir, string string, Strstream stream) {returnDir.listfiles (NewFileFilter () {@Override Public BooleanAccept (file file) {returnStream.string (String). Like () | |File.isfile ();    }        }); }}

Java Scan Package

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.