【问题标题】:Java: how to scan classes without knowing package names?Java:如何在不知道包名的情况下扫描类?
【发布时间】:2018-02-15 18:08:58
【问题描述】:

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

我找到了这些方法:

Package.getPackages()

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

ClassPathScanningCandidateComponentProvider.findCandidateComponents(basePackageName)

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


编辑回复@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);
        }
    }
}

【问题讨论】:

  • 您不能将 bean 直接注入静态字段。所以去掉静电。
  • 已修改,appContext 上仍为空指针。
  • 如果您使用的是spring-boot,请参考以下链接,该链接演示了如何设置spring应用程序。 projects.spring.io/spring-boot 。应用程序类由您实例化,而不是由 spring 实例化。希望你能理解。
  • 我没有使用 Spring-Boot,这是缺少一点...如果我没记错 Spring-Boot 启动服务器,我不确定制作一个 api 是否可行启动服务器...

标签: java spring reflection packages classloading


【解决方案1】:

假设你有一个自定义注解 @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();
   }
}

【讨论】:

  • 我正在制作一个独立的应用程序,而不是一个 Web 应用程序,@Autowired 和 ApplicationContext 也可以工作吗?
  • 我在 appContext 上得到 NullPointer。
  • 你用@Component 注释了你当前的类吗?
  • 是的,我确实用@Component 注释了我的类。无论如何,没有注入的是applicationContext,而不是bean。
  • 猜想applicationcontext没有正确注入,能分享下你的代码吗?
猜你喜欢
  • 2016-07-19
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多