0

I am creating a program which uses reflection to register some annotated interface and stores the class names for latter use. I can retrieve the annotated classes pretty easily but know my question is: assuming that each of these interfaces is instantiated as a singleton, would be possible to retrieve the actual instance of the class from the class name? Please notice that I already know how to instantiate a new oject. But can I get one that already exists? I've googled it for a while and I've only found the Class.forName() method which I think is not what I am looking for (may be wrong though). In my project I'm also using Spring, so I'm also open to Spring solutions. Any help is really appreciated.

Thank you!

EDIT : This is how I am getting the annotated 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());
Aurasphere
  • 3,841
  • 12
  • 44
  • 71
  • Does the class have a static method that returns the singleton reference? – Patricia Shanahan Oct 13 '15 at 08:24
  • No, the classes are instantiated by Spring. I'll add what I tryed so far in my answer. – Aurasphere Oct 13 '15 at 08:32
  • "But can I get one that already exists?" Highlander would ask: which one, there could be many? –  Oct 13 '15 at 08:32
  • You cannot instantiate an interface... – M. Deinum Oct 13 '15 at 08:34
  • @RC You are right, that's exactly why I'm pointing out that I'm working with singletons. Still I'm not sure if it's possibile... M. Deinum I'm not instatiating an Interface. I have already instantiated a class that implements an interface. Now I'd like to get that object... – Aurasphere Oct 13 '15 at 08:43

1 Answers1

1

Just query Spring application context, for example with ListableBeanFactory.html#getBeansOfType. There was also similar question about singletons: How can I get a list of instantiated beans from Spring?

Community
  • 1
  • 1
user158037
  • 2,659
  • 1
  • 24
  • 27