Java traverses all classes in the package

Source: Internet
Author: User

As required by the project, I want to obtain all the classes under a certain package (including all the sub-packages of this package) and find them online. There is nothing available, even if you find something to write, the efficiency is low. Simply write it on your own, and exercise your skills in writing code. I would like to share with you the hope to help you ......
[Java]
Package com. itkt. mtravel. hotel. util;
 
Import java. io. File;
Import java. util. ArrayList;
Import java. util. List;
 
Public class PackageUtil {

Public static void main (String [] args ){
String packageName = "com. itkt. mtravel. hotel ";
 
List <String> classNames = getClassName (packageName );
For (String className: classNames ){
System. out. println (className );
}
}
 
Public static List <String> getClassName (String packageName ){
String filePath = ClassLoader. getSystemResource (""). getPath () + packageName. replace (".","\\");
List <String> fileNames = getClassName (filePath, null );
Return fileNames;
}
 
Private static List <String> getClassName (String filePath, List <String> className ){
List <String> myClassName = new ArrayList <String> ();
File file = new File (filePath );
File [] childFiles = file. listFiles ();
For (File childFile: childFiles ){
If (childFile. isDirectory ()){
MyClassName. addAll (getClassName (childFile. getPath (), myClassName ));
} Else {
String childFilePath = childFile. getPath ();
ChildFilePath = childFilePath. substring (childFilePath. indexOf ("\ classes") + 9, childFilePath. lastIndexOf ("."));
ChildFilePath = childFilePath. replace ("\\",".");
MyClassName. add (childFilePath );
}
}
 
Return myClassName;
}
}
Nothing is especially complicated. You can understand it basically. If the namespace of any package is input, all classes under the package can be returned. I feel pretty good, easy to use, general and scalable. As a matter of fact, after skilled basic skills, the rest is the idea of assembly.

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.