Can you find all classes in a package using reflection?

前端 未结 27 2148
不知归路
不知归路 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 05:47

    You should probably take a look at the open source Reflections library. With it you can easily achieve what you want.

    First, setup the reflections index (it's a bit messy since searching for all classes is disabled by default):

    List classLoadersList = new LinkedList();
    classLoadersList.add(ClasspathHelper.contextClassLoader());
    classLoadersList.add(ClasspathHelper.staticClassLoader());
    
    Reflections reflections = new Reflections(new ConfigurationBuilder()
        .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
        .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
        .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("org.your.package"))));
    

    Then you can query for all objects in a given package:

    Set> classes = reflections.getSubTypesOf(Object.class);
    

提交回复
热议问题