【问题标题】:Retrieving instance of a class from class name从类名中检索类的实例
【发布时间】:2015-10-13 08:22:47
【问题描述】:

我正在创建一个程序,它使用反射来注册一些带注释的接口并存储类名以供以后使用。我可以很容易地检索带注释的类,但我知道我的问题是:假设这些接口中的每一个都被实例化为单例,是否可以从类名中检索类的实际实例?请注意,我已经知道如何实例化一个新对象。但是我可以得到一个已经存在的吗?我已经用谷歌搜索了一段时间,但我只找到了 Class.forName() 方法,我认为这不是我想要的(虽然可能是错误的)。在我的项目中,我也在使用 Spring,所以我也对 Spring 解决方案持开放态度。非常感谢任何帮助。

谢谢!

编辑:这就是我获取带注释的类的方式:

ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false);
    componentProvider.addIncludeFilter(new AnnotationTypeFilter(AuraInput.class));
    componentProvider.addIncludeFilter(new AnnotationTypeFilter(AuraOutput.class));
    for(BeanDefinition bd : componentProvider.findCandidateComponents("com")){
        System.out.println("Interface: " + bd.getBeanClassName());

//The if checks if the class it's an instance of InputInterface

if(InputInterface.class.isAssignableFrom(Class.forName(bd.getBeanClassName()))) 

//Here I want to call a method of InputInterface which gives back a string... But how do I get the actual object assuming I have the class name?

System.out.println(((InputInterface) Class.forName(bd.getBeanClassName())).getInterfaceName());

【问题讨论】:

  • 类是否有返回单例引用的静态方法?
  • 不,这些类是由 Spring 实例化的。我会在我的答案中添加到目前为止我尝试过的内容。
  • "但是我可以得到一个已经存在的吗?"汉兰达会问:哪一个,可能有很多?
  • 你不能实例化一个接口...
  • @RC 你说得对,这正是我指出我正在使用单例的原因。仍然我不确定它是否可能...... M. Deinum 我没有实例化接口。我已经实例化了一个实现接口的类。现在我想得到那个对象......

标签: java spring reflection


【解决方案1】:

只需查询 Spring 应用程序上下文,例如使用 ListableBeanFactory.html#getBeansOfType。还有关于单例的类似问题:How can I get a list of instantiated beans from Spring?

【讨论】:

  • 这正是我想要的。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多