atmaish
atmaish

Reputation: 2613

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

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?

Upvotes: 8

Views: 2646

Answers (2)

Ralph
Ralph

Reputation: 120851

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.

Upvotes: 13

Peter Svensson
Peter Svensson

Reputation: 6173

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)

Upvotes: 2

Related Questions