Keep track of all the classes that implement a particular interface?

走远了吗. 提交于 2020-01-02 02:25:11

问题


It's difficult to explain what I really want. I have an interface which has a method getRuntimeInfo() which provides me all the runtime debug information for the variables of a class. I want to see the list of all the classes that implement this interface. I am using Java and Spring. One way I can do this is to get all the beans from the Spring Context and check using the instanceof operator. But i wouldn't want to do that for obvious performance impacts. Do i have some other option?


回答1:


What about this solution:

@Component
public class WithAllMyInterfaceImpls {

  @Autowire
  List<MyInterface> allBeansThatImplementTheMyInterface;

}

The List is only populated once (at start up) so it should not have a significant impact in the "normal" runtime performance.


Comment:

can you explain your code

You know Spring is a IOC Container. @Component tells Spring that it should create an instance of this class (a so called Spring Managed Bean). IOC means also that the Container is responsible to inject references to other instances (Spring Managed Beans). @Autowire (as well as @Resource and @Inject -- all do the same) is such an annotation that tells Spring that this field should be populated by Spring. Spring itself tries to figure out with what instances the field should be populates. A default technique that spring uses is by type this means that Spring inspect the type of the field, and search for matching beans. In your case it is a generic List - this is a bit special. In this case Spring populate the field with an list, where the elements are all beans that match the generic type.




回答2:


How about the getBeansOfType method from ApplicationContext? It returns a Map of the beans implementing your interface?

http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/beans/factory/ListableBeanFactory.html#getBeansOfType(java.lang.Class)



来源:https://stackoverflow.com/questions/9143419/keep-track-of-all-the-classes-that-implement-a-particular-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!