Can you find all classes in a package using reflection?

前端 未结 27 2268
不知归路
不知归路 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:01

    Without using any extra libraries:

    package test;
    
    import java.io.DataInputStream;
    import java.io.InputStream;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) throws Exception{
            List classes = getClasses(Test.class.getClassLoader(),"test");
            for(Class c:classes){
                System.out.println("Class: "+c);
            }
        }
    
        public static List getClasses(ClassLoader cl,String pack) throws Exception{
    
            String dottedPackage = pack.replaceAll("[/]", ".");
            List classes = new ArrayList();
            URL upackage = cl.getResource(pack);
    
            DataInputStream dis = new DataInputStream((InputStream) upackage.getContent());
            String line = null;
            while ((line = dis.readLine()) != null) {
                if(line.endsWith(".class")) {
                   classes.add(Class.forName(dottedPackage+"."+line.substring(0,line.lastIndexOf('.'))));
                }
            }
            return classes;
        }
    }
    

提交回复
热议问题