从 class 名称中检索 class 的实例
Retrieving instance of a class from class name
我正在创建一个程序,它使用反射来注册一些带注释的接口并存储 class 名称供以后使用。我可以很容易地检索带注释的 classes 但我知道我的问题是:假设这些接口中的每一个都被实例化为单例,将有可能从 [= 检索 class 的实际实例22=]名字?请注意,我已经知道如何实例化一个新对象。但是我能得到一个已经存在的吗?我用谷歌搜索了一段时间,只找到了 Class.forName() 方法,我认为这不是我要找的方法(虽然可能是错误的)。在我的项目中,我也使用 Spring,所以我也对 Spring 解决方案持开放态度。非常感谢任何帮助。
谢谢!
EDIT :这就是我获得带注释的 classes 的方式:
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 应用上下文,例如 ListableBeanFactory.html#getBeansOfType. There was also similar question about singletons: How can I get a list of instantiated beans from Spring?
我正在创建一个程序,它使用反射来注册一些带注释的接口并存储 class 名称供以后使用。我可以很容易地检索带注释的 classes 但我知道我的问题是:假设这些接口中的每一个都被实例化为单例,将有可能从 [= 检索 class 的实际实例22=]名字?请注意,我已经知道如何实例化一个新对象。但是我能得到一个已经存在的吗?我用谷歌搜索了一段时间,只找到了 Class.forName() 方法,我认为这不是我要找的方法(虽然可能是错误的)。在我的项目中,我也使用 Spring,所以我也对 Spring 解决方案持开放态度。非常感谢任何帮助。
谢谢!
EDIT :这就是我获得带注释的 classes 的方式:
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 应用上下文,例如 ListableBeanFactory.html#getBeansOfType. There was also similar question about singletons: How can I get a list of instantiated beans from Spring?