java从类名中检索类的实例
我正在创建一个程序,它使用反射来注册一些带注释的接口,并存储类名以供以后使用。我可以很容易地检索带注释的类,但我知道我的问题是:假设这些接口中的每一个都被实例化为一个单例,那么是否可以从类名中检索类的实际实例?请注意,我已经知道如何实例化一个新项目。但我能得到一个已经存在的吗?我在谷歌上搜索了一段时间,只找到了这个类。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());
# 1 楼答案
只需查询Spring应用程序上下文,例如使用ListableBeanFactory.html#getBeansOfType。关于单身汉也有类似的问题:How can I get a list of instantiated beans from Spring?