Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 202
atmaish Avatar asked Feb 04 '12 18:02

atmaish


1 Answers

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.

like image 57
Ralph Avatar answered Nov 15 '22 15:11

Ralph