Can you find all classes in a package using reflection?

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

    Worth mentioning

    If you want to have a list of all classes under some package, you can use Reflection the following way:

    List myTypes = new ArrayList<>();
    
    Reflections reflections = new Reflections("com.package");
    for (String s : reflections.getStore().get(SubTypesScanner.class).values()) {
        myTypes.add(Class.forName(s));
    }
    

    This will create a list of classes that later you can use them as you wish.

提交回复
热议问题