Can you find all classes in a package using reflection?

前端 未结 27 2281
不知归路
不知归路 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:44

    Spring

    This example is for Spring 4, but you can find the classpath scanner in earlier versions as well.

    // create scanner and disable default filters (that is the 'false' argument)
    final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
    // add include filters which matches all the classes (or use your own)
    provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
    
    // get matching classes defined in the package
    final Set classes = provider.findCandidateComponents("my.package.name");
    
    // this is how you can load the class type from BeanDefinition instance
    for (BeanDefinition bean: classes) {
        Class clazz = Class.forName(bean.getBeanClassName());
        // ... do your magic with the class ...
    }
    

    Google Guava

    Note: In version 14, the API is still marked as @Beta, so beware in production code.

    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    
    for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
      if (info.getName().startsWith("my.package.")) {
        final Class clazz = info.load();
        // do something with your clazz
      }
    }
    

提交回复
热议问题