Can you find all classes in a package using reflection?

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

    The most robust mechanism for listing all classes in a given package is currently ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author.)

    List classNames = new ArrayList<>();
    try (ScanResult scanResult = new ClassGraph().acceptPackages("my.package")
            .enableClassInfo().scan()) {
        classNames.addAll(scanResult.getAllClasses().getNames());
    }
    

提交回复
热议问题