1

我正在编写一个 API,它提供基于类注释的功能。API 将被导入,因此它不知道客户端的包。所以问题是:如何在不知道包名的情况下扫描类?

我找到了这些方法:

Package.getPackages()

但它只返回包的一个子集。

ClassPathScanningCandidateComponentProvider.findCandidateComponents(basePackageName)

但 is 不接受通配符,例如*or .


编辑对@Rakesh 的回答

@Component
public class Application {

    @Autowired
    public ApplicationContext appContext;

    public static void main(String[] args) {
        Application a = new Application();
        String[] beanNames=a.appContext.getBeanNamesForAnnotation(Run.class);
        for (String beanName : beanNames) {
            System.out.println(beanName);
            Object bean = a.appContext.getBean(beanName);
            Class<? extends Object> class1 = bean.getClass();
            System.out.println(class1);
        }
    }
}
4

1 回答 1

0

假设您有一个自定义注释@CustomAnnotation,并且您已经A像这样用它注释了一个类

@CustomAnnotation
@Component
public class A{
 ...
}

现在,如果您注入应用程序上下文,您可以像这样获得这些类

@Autowired
ApplicationContext appContext;
.
.
.
someMethod(){

  string[] beanNames=appContext.getBeanNamesForAnnotation(CustomAnnotation.class);
   for (val beanName : beanNames) {
      Object bean = appContext.getBean(beanName);
      Class<? extends Object> class1 = bean.getClass();
   }
}
于 2018-02-15T08:38:00.753 回答