Can you find all classes in a package using reflection?

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

    Aleksander Blomskøld's solution did not work for me for parameterized tests @RunWith(Parameterized.class) when using Maven. The tests were named correctly and also where found but not executed:

    -------------------------------------------------------
    T E S T S
    -------------------------------------------------------
    Running some.properly.named.test.run.with.maven.SomeTest
    Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.123 sec
    

    A similar issue has been reported here.

    In my case @Parameters is creating instances of each class in a package. The tests worked well when run locally in the IDE. However, when running Maven no classes where found with Aleksander Blomskøld's solution.

    I did make it work with the following snipped which was inspired by David Pärsson's comment on Aleksander Blomskøld's answer:

    Reflections reflections = new Reflections(new ConfigurationBuilder()
                .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
                .addUrls(ClasspathHelper.forJavaClassPath()) 
                .filterInputsBy(new FilterBuilder()
                .include(FilterBuilder.prefix(basePackage))));
    
    Set> subTypesOf = reflections.getSubTypesOf(Object.class);
    

提交回复
热议问题