I want to recursively search the class list under the package

As a system engineer of SIer, I spend every day earning daily money, but recently I had the opportunity to create a design document (?) That says, "List the created Java classes by giving them package names." It's a reckless story that manual work is troublesome because of the number of Java classes created. Therefore, I decided to write a program that recursively searches for __packages and outputs a list of classes with package names. Below is a sample.

image

For example, if you have a project with the above package structure, the program that outputs the classes under "jp.co" with the package name should be as follows.

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Enumeration;
import java.util.PriorityQueue;

public class Main {
    
    private static final String PACKAGE_SEPARATOR = ".";
    
    private static final String CLASS_SUFFIX = ".class";
    
    public static void main(String[] args) throws IOException, URISyntaxException {
        //Use the class loader to get the resources under the package.
        String rootPackageName = "jp.co".replace(PACKAGE_SEPARATOR, File.separator);
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        Enumeration<URL> rootUrls = classLoader.getResources(rootPackageName);
        
        //Recursively search directories".class"If you find a file that ends with
        //After formatting the character string, store it in the list.
        PriorityQueue<String> classNames = new PriorityQueue();
        while (rootUrls.hasMoreElements()) {
            URL rootUrl = rootUrls.nextElement();
            Path rootPath = Paths.get(rootUrl.toURI());
           
            Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>(){
                @Override
                public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                    String pathName = path.toString();
                    if (pathName.endsWith(CLASS_SUFFIX)) {
                        int beginIndex = pathName.lastIndexOf(rootPackageName);
                        int endIndex = pathName.lastIndexOf(CLASS_SUFFIX);
                        String className = pathName.substring(beginIndex, endIndex)
                                                   .replace(File.separator, PACKAGE_SEPARATOR);
                        
                        classNames.add(className);
                    }
                    
                    return super.visitFile(path, attrs);
                }
            });
        }
        
        //Output a list of found class names.
        for (String className : classNames) {
            System.out.println(className);
        }
        
        /*
        jp.co.first.ClassA
        jp.co.first.ClassB
        jp.co.first.sub.ClassC
        jp.co.first.sub.ClassD
        jp.co.second.ClassE
        jp.co.second.ClassF
        */
    }
}

Recommended Posts

I want to recursively search the class list under the package
I want to recursively search for files under a specific directory
I want to recursively get the superclass and interface of a certain class
I want to display the images under assets/images in the production environment
Glassfish tuning list that I want to keep for the time being
I want to output the day of the week
I want to var_dump the contents of the intent
I want to truncate after the decimal point
I want to get the value in Ruby
I want to call a method of another class
[Java] I want to calculate the difference from the date
I want to embed any TraceId in the log
I learned stream (I want to convert List to Map <Integer, List>)
I want to know the answer of the rock-paper-scissors app
I want to display the name of the poster of the comment
I want to dark mode with the SWT app
I want to call the main method using reflection
[Rough commentary] I want to marry the pluck method
I want to be aware of the contents of variables!
I want to return the scroll position of UITableView!
I want to simplify the log output on Android
I want to add a delete function to the comment function
I want to set the conditions to be displayed in collection_check_boxes
[Rails] [bootstrap] I want to change the font size responsively
I want to use screen sharing on the login screen on Ubuntu 18
(ยด-`) .. oO (I want to easily find the standard output "Hello".
I want to bring Tomcat to the server and start the application
I want to expand the clickable part of the link_to method
I want to change the log output settings of UtilLoggingJdbcLogger
I want to make a list with kotlin and java!
I want to call a method and count the number
I want to use the Java 8 DateTime API slowly (now)
I want to create a form to select the [Rails] category
I want to put the JDK on my Mac PC
How to mock some methods of the class under test
I want to distinct the duplicated data with has_many through
I want to transition to the same screen in the saved state
I want to narrow down the display of docker ps
I want to return multiple return values for the input argument
[Ruby] I want to reverse the order of the hash table
I want to temporarily disable the swipe gesture of UIPageViewController
I want to pass the startup command to postgres with docker-compose.
I want to simplify the conditional if-else statement in Java
I want to judge the necessity of testing by comparing the difference of class files when refactoring Java
[Java] I want to check that the elements in the list are null or empty [Collection Utils]
I want to create a chat screen for the Swift chat app!
I want to understand the flow of Spring processing request parameters
I want to return to the previous screen with kotlin and java!
The story of Collectors.groupingBy that I want to keep for posterity
If you want to include the parent class in Lombok's @builder
[Eclipse] I want to open the same file twice [Split editor]
I want to add the disabled option to f.radio_button depending on the condition
I want to remove the top margin in Grouped UITableView (swift)
[Java] I want to perform distinct with the key in the object
I want to control the default error message of Spring Boot
I want to change the value of Attribute in Selenium of Ruby
[Android] I want to get the listener from the button in ListView
Swift: I want to chain arrays
I want to use FormObject well
How to use the wrapper class
I want to convert InputStream to String