Can you find all classes in a package using reflection?

前端 未结 27 2278
不知归路
不知归路 2020-11-21 05:24

Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)

27条回答
  •  眼角桃花
    2020-11-21 06:08

    It is very possible, but without additional libraries like Reflections it is hard...
    It is hard because you haven't full instrument for get class name.
    And, I take the code of my ClassFinder class:

    package play.util;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.List;
    import java.util.jar.JarEntry;
    import java.util.jar.JarFile;
    
    /**
     * Created by LINKOR on 26.05.2017 in 15:12.
     * Date: 2017.05.26
     */
    public class FileClassFinder {
    private JarFile file;
    private boolean trouble;
    public FileClassFinder(String filePath) {
        try {
            file = new JarFile(filePath);
        } catch (IOException e) {
            trouble = true;
        }
    }
    
    public List findClasses(String pkg) {
        ArrayList classes = new ArrayList<>();
        Enumeration entries = file.entries();
        while (entries.hasMoreElements()) {
            JarEntry cls = entries.nextElement();
            if (!cls.isDirectory()) {
                String fileName = cls.getName();
                String className = fileName.replaceAll("/",         ".").replaceAll(File.pathSeparator, ".").substring(0, fileName.lastIndexOf('.'));
                if (className.startsWith(pkg)) classes.add(className.substring(pkg.length() + 1));
            }
        }
        return classes;
    }
    }
    

提交回复
热议问题