Find out which classes of a given API are used

后端 未结 8 887
鱼传尺愫
鱼传尺愫 2020-11-29 06:20

In a Java Project of mine, I would like to find out programmatically which classes from a given API are used. Is there a good way to do that? Through source code parsing or

8条回答
  •  一整个雨季
    2020-11-29 06:47

    Something like this perhaps:

    import java.io.*;
    import java.util.Scanner;
    import java.util.regex.Pattern;
    
    public class FileTraverser {
    
        public static void main(String[] args) {
            visitAllDirsAndFiles(new File("source_directory"));
        }
    
        public static void visitAllDirsAndFiles(File root) {
            if (root.isDirectory())
                for (String child : root.list())
                    visitAllDirsAndFiles(new File(root, child));
            process(root);
        }
    
        private static void process(File f) {
    
            Pattern p = Pattern.compile("(?=\\p{javaWhitespace}*)import (.*);");
            if (f.isFile() && f.getName().endsWith(".java")) {
                try {
                    Scanner s = new Scanner(f);
                    String cls = "";
                    while (null != (cls = s.findWithinHorizon(p, 0)))
                        System.out.println(cls);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    You may want to take comments into account, but it shouldn't be too hard. You could also make sure you only look for imports before the class declaration.

提交回复
热议问题