In Java, all classes under the package are obtained through the package name

Source: Internet
Author: User

The first thing to do in MyBatis is to automatically create an item that updates the table structure through annotations, where the class of all entity classes is acquired after spring is loaded, to get annotations on the attributes of the entity class, and to analyze the table structure to create a modified table structure.

So you need a function to get all the classes under the package by the package name, then directly paste the code:

 PackageCom.sunchenbin.store.utils;ImportJava.io.File;ImportJava.io.FileFilter;ImportJava.io.IOException;ImportJava.net.JarURLConnection;ImportJava.net.URL;ImportJava.net.URLDecoder;ImportJava.util.Enumeration;ImportJava.util.LinkedHashSet;ImportJava.util.Set;ImportJava.util.jar.JarEntry;ImportJava.util.jar.JarFile;/** * Get class * by package name * * @author sunchenbin * @version June 23, 2016 PM 5:55:18 * * Public  class classtools{    /** * Get all class * * @param pack * @return  * * from the Package     Public StaticSet<class<?>>getclasses(String pack) {//A collection of the first class classset<class<?>> classes =NewLinkedhashset<class<?>> ();//Whether loop iteration        Booleanrecursive =true;//Get the name of the package and replace itString PackageName = pack; String packagedirname = Packagename.replace ('. ','/');//Define a set of enumerations to be combined for looping to handle things under this directoryEnumeration<url> dirs;Try{dirs = Thread.CurrentThread (). Getcontextclassloader (). Getresources (Packagedirname);//loop iteration down             while(Dirs.hasmoreelements ()) {//Get Next elementURL url = dirs.nextelement ();//Get the name of the agreementString protocol = Url.getprotocol ();//If it is saved as a file on the server                if("File". Equals (protocol)) {SYSTEM.ERR.PRINTLN ("File type of scan");//Get the physical path of the packageString FilePath = Urldecoder.decode (Url.getfile (),"UTF-8");//Scan files under the entire package in a file and add them to the collectionFindandaddclassesinpackagebyfile (PackageName, FilePath, recursive, classes); }Else if("Jar". Equals (protocol)) {//If it is a jar package file                    //define a jarfileSystem.err.println ("jar-type Scan"); Jarfile jar;Try{//Get jarJar = ((jarurlconnection) url.openconnection ()). Getjarfile ();//Get an enumeration class from this jar packageenumeration<jarentry> entries = Jar.entries ();//The same loop iteration                         while(Entries.hasmoreelements ()) {//Get an entity in the jar can be a directory and some other files in the jar package such as meta-inf filesJarentry entry = Entries.nextelement (); String name = Entry.getname ();//If it starts with/                            if(Name.charat (0) =='/') {//Get the following stringName = Name.substring (1); }//If the first half and the defined package name are the same                            if(Name.startswith (Packagedirname)) {intIDX = Name.lastindexof ('/');//If the end of the "/" is a package                                if(IDX! =-1) {//Get package name replace "/" with "."PackageName = name.substring (0, IDX). Replace ('/','. '); }//If it can be iterated and is a package                                if(IDX! =-1) || Recursive) {//If it is a. class file and is not a directory                                    if(Name.endswith (". Class") &&!entry.isdirectory ()) {//Remove the ". Class" from the back to get the real class nameString className = name.substring (packagename.length () +1, Name.length ()-6);Try{//Add to ClassesClasses.add (Class.forName (PackageName +'. '+ className)); }Catch(ClassNotFoundException e) {//Log                                            //. Error ("Add user Custom view class errors cannot find the. class file for this class");E.printstacktrace ();                        }                                    }                                }                            } }                    }Catch(IOException e) {//Log.error ("Error getting file from Jar package while scanning user defined view");E.printstacktrace (); }                }            }        }Catch(IOException e)        {E.printstacktrace (); }returnClasses }/** * In the form of a file to get all class * * @param packagename * @param * @pa Ram Recursive * @param classes * /     Public Static void Findandaddclassesinpackagebyfile(String PackageName, String PackagePath,Final BooleanRecursive, set<class<?>> classes) {//Get the directory for this package to create a fileFile dir =NewFile (PackagePath);//If it does not exist or is not a directory, return directly        if(!dir.exists () | |!dir.isdirectory ()) {//Log.warn ("User Defined package name" + PackageName + "without any files");            return; }//If it exists, get all files under the package including directoryfile[] Dirfiles = Dir.listfiles (NewFileFilter () {//Custom filter rules If you can loop (including subdirectories) or files ending with a. Class (Compiled Java class file)             Public Boolean Accept(File file) {return(Recursive && file.isdirectory ()) | | (File.getname (). EndsWith (". Class")); }        });//Loop All Files         for(File file:dirfiles) {//If it is a directory then continue scanning            if(File.isdirectory ()) {Findandaddclassesinpackagebyfile (PackageName +"."+ File.getname (), File.getabsolutepath (), recursive, classes); }Else{//If the Java class file is removed, the following. Class only leaves the class nameString className = File.getname (). SUBSTRING (0, File.getname (). Length ()-6);Try{//Add to the collection                    //Classes.add (Class.forName (PackageName + '. ' +                    //ClassName));                    //After replying to the classmate's reminder, here with forname some bad, will trigger the static method, no use of ClassLoader load cleanClasses.add (Thread.CurrentThread (). Getcontextclassloader (). LoadClass (PackageName +'. '+ className)); }Catch(ClassNotFoundException e) {///Log.error ("Add user Custom view class error cannot find this class of. class file");E.printstacktrace (); }            }        }    }}

In Java, all classes under the package are obtained through the package name

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.