跟踪实现特定接口的所有类? [英] Keep track of all the classes that implement a particular interface?

查看:129
本文介绍了跟踪实现特定接口的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很难解释我真正想要的东西。我有一个接口,它有一个方法 getRuntimeInfo(),它为我提供了类的变量的所有运行时调试信息。我想查看实现此接口的所有类的列表。我正在使用Java和Spring。
我可以这样做的一种方法是从Spring Context获取所有bean并使用 instanceof 运算符进行检查。但我不希望这样做对明显的性能影响。我还有其他选择吗?

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?

推荐答案

这个解决方案怎么样:

@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.

评论:


你能解释一下你的代码吗?

can you explain your code

你知道Spring是一个IOC容器。 @Component 告诉Spring它应该创建这个类的实例(一个所谓的 Spring Managed Bean )。 IOC还意味着Container负责注入对其他实例的引用(Spring Managed Beans)。 @Autowire (以及 @Resource @Inject - 所有这些都是这样的注释,告诉Spring这个字段应该由Spring填充。 Spring本身试图找出该字段应该填充的实例。 spring使用的默认技术是类型这意味着Spring检查字段的类型,并搜索匹配的bean。在你的情况下,它是一个通用列表 - 这有点特殊。在这种情况下,Spring使用列表填充字段,其中元素是与泛型类型匹配的所有bean。

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.

这篇关于跟踪实现特定接口的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆