Java traverses all classes in a package

Source: Internet
Author: User
Tags addall

PackageUtil class

import java.io.file;import java.net.url;import java.net.urlclassloader;import Java.util.arraylist;import Java.util.enumeration;import java.util.list;import java.util.jar.jarentry;import java.util.jar.JarFile;/** * Get all the classes in the package * @author **/ Public classPackageUtil { Public Static voidMain (string[] args) throws Exception {String PackageName="Com.wang.vo.request.hotel"; //list<string> classnames = GetClassName (packagename);list<string> classnames = GetClassName (PackageName,false); if(Classnames! =NULL) {             for(String classname:classnames) {System. out. println (ClassName); }        }    }    /** * Get all Classes under a package (including all child packages of the package) * * @param packagename * Package name * @return The full name of the class*/     Public StaticList<string>getclassname (String packagename) {returnGetClassName (PackageName,true); }    /** * get all classes under a package * * @param packagename * Package name * @param childpackage * Whether to traverse the child package * Full name of @return class*/     Public StaticList<string>GetClassName (String packagename, Boolean childpackage) {List<String> FileNames =NULL; ClassLoader Loader=Thread.CurrentThread (). Getcontextclassloader (); String PackagePath= Packagename.replace (".","/"); URL URL=Loader.getresource (PackagePath); if(URL! =NULL) {String type=Url.getprotocol (); if(Type.equals ("file") ) {FileNames= Getclassnamebyfile (Url.getpath (),NULL, Childpackage); } Else if(Type.equals ("Jar") ) {FileNames=Getclassnamebyjar (Url.getpath (), childpackage); }        } Else{fileNames=Getclassnamebyjars (((urlclassloader) loader). Geturls (), PackagePath, childpackage); }        returnFileNames; }    /** * get all classes under a package from the project file * * @param filePath * File path * @param className * Class Name Collection * @param childpackage * Whether to traverse the full name of the child package * @return Class*/    Private StaticList<string> Getclassnamebyfile (String FilePath, list<string>ClassName, Boolean childpackage) {List<String> myClassName =NewArraylist<>(); File File=NewFile (FilePath); File[] Childfiles=File.listfiles ();  for(File childfile:childfiles) {if(Childfile.isdirectory ()) {if(childpackage) {Myclassname.addall (Getclassnamebyfile (Childfile.getpath (), myClassName, ChildPac                Kage)); }            } Else{String Childfilepath=Childfile.getpath (); if(Childfilepath.endswith (". Class") ) {Childfilepath= Childfilepath.substring (Childfilepath.indexof ("\\classes") +9, Childfilepath.lastindexof (".")); Childfilepath= Childfilepath.replace ("\\",".");                Myclassname.add (Childfilepath); }            }        }        returnmyClassName; }    /** * get all classes under a package from the jar * * @param jarpath * jar file path * @param childpackage * Yes No traversal of the full name of the child package * @return Class*/    Private StaticList<string>Getclassnamebyjar (String jarpath, Boolean childpackage) {List<String> myClassName =NewArraylist<>(); String[] Jarinfo= Jarpath.split ("!"); String Jarfilepath= jarinfo[0].substring (jarinfo[0].indexof ("/")); String PackagePath= jarinfo[1].substring (1); Try{jarfile Jarfile=NewJarfile (Jarfilepath); Enumeration<JarEntry> Entrys =jarfile.entries ();  while(Entrys.hasmoreelements ()) {Jarentry Jarentry=entrys.nextelement (); String EntryName=Jarentry.getname (); if(Entryname.endswith (". Class")) {                    if(childpackage) {if(Entryname.startswith (PackagePath)) {EntryName= Entryname.replace ("/","."). SUBSTRING (0, Entryname.lastindexof ("."));                        Myclassname.add (EntryName); }                    } Else {                        intindex = Entryname.lastindexof ("/");                        String Mypackagepath; if(Index! =-1) {Mypackagepath= Entryname.substring (0, index); } Else{Mypackagepath=EntryName; }                        if(Mypackagepath.equals (PackagePath)) {EntryName= Entryname.replace ("/","."). SUBSTRING (0, Entryname.lastindexof ("."));                        Myclassname.add (EntryName); }                    }                }            }        } Catch(Exception e) {e.printstacktrace (); }        returnmyClassName; }    /** * Search for the package from all jars and get all classes under the package * * @param URLs * URL Collection * @param packagepath * Package path * @param childpackage * Whether to traverse the full name of the child package * @return Class*/    Private StaticList<string>Getclassnamebyjars (url[] URLs, String PackagePath, Boolean childpackage) {List<String> myClassName =NewArraylist<>(); if(URLs! =NULL) {             for(inti =0; i < urls.length; i++) {URL URL=Urls[i]; String URLPath=Url.getpath (); //You do not have to search the classes folder                if(Urlpath.endswith ("classes/")) {                    Continue; } String Jarpath= URLPath +"!/"+PackagePath;            Myclassname.addall (Getclassnamebyjar (Jarpath, childpackage)); }        }        returnmyClassName; }}

Since we are not sure which way the jar package was built, if we adopt the default method of generating the jar package, we pass the Thread.CurrentThread (). Getcontextclassloader (). GetResource () is not available , thus adding a package domain name from all of the jar packages, so the functionality is much better.

Reprint to Https://www.2cto.com/kf/201211/169865.html

Java traverses all classes in a 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.