0

I have few classes in a package, that all implement the same interface. I'd like to get all these classes dynamically, to execute a method. Is that possible in java? If not, how can i do something similar. Should i use reflection?

Thanks

Axel
  • 165
  • 3
  • 14
  • 1
    Does this answer your question? [How can I get a list of all the implementations of an interface programmatically in Java?](https://stackoverflow.com/questions/347248/how-can-i-get-a-list-of-all-the-implementations-of-an-interface-programmatically) – Alexandru Somai Mar 03 '20 at 09:58
  • You never should use reflection unless you know what you're doing and what drawbacks it has. Other than that, it is unclear to me what you wan to do. What do you mean by "get all classes dynamically"? – Amongalen Mar 03 '20 at 09:59
  • @Amongalen Sorry if it's not clear, i will try to explain better. I have few classes in a package, and i want to loop through this package and execute a given method for each class. Knowing that every classes are implementing a single interface. – Axel Mar 03 '20 at 10:02
  • @AlexandruSomai Yes it does, thanks – Axel Mar 03 '20 at 10:07
  • @AlexandruSomai Even though you can use reflection, in 99% of all cases people try to use it to solve their problem the wrong way. Could you expand why you want to get all implementations of an interface to then execute a method on them? – Wesley De Keirsmaeker Mar 03 '20 at 10:12
  • I have to make differents test of differents web services in my app. I'd like to make a class for each different tests, and then being able to loop throught each class to get every test result. Hopefully that's clear, sorry if it's not. – Axel Mar 03 '20 at 10:15

1 Answers1

0

You can use extcos library. https://sourceforge.net/projects/extcos/ For more details, you can refer the mentioned link

Set<Class<? extends MyInterface>> classes = new HashSet<Class<? extends MyInterface>>();

    ComponentScanner scanner = new ComponentScanner();
    scanner.getClasses(new ComponentQuery() {

        protected void query() {
            select().
            from("my.package1").
            andStore(thoseImplementing(MyInterface.class).into(classes)).
            returning(none());
        }
    });
akshaya pandey
  • 997
  • 6
  • 16