How to get only realistic classes with reflections

I use the reflections package to get a set of classes that implement a specific interface. This set will be used as a list of possible command line options. My problem is that I want to get only real classes, but right now I get both valid and uninteresting classes (for example, abstract classes) from the following code:

Map<String, Class<? extends InterfaceOptimizer>> optimizerList = new HashMap<String, Class<? extends InterfaceOptimizer>>(); Reflections reflections = new Reflections("eva2.optimization.strategies"); Set<Class<? extends InterfaceOptimizer>> optimizers = reflections.getSubTypesOf(InterfaceOptimizer.class); for(Class<? extends InterfaceOptimizer> optimizer : optimizers) { optimizerList.put(optimizer.getName(), optimizer); } 

Is there a way to filter the set returned by getSubTypesOf in order to filter out abstract classes?

+6
source share
2 answers

Use the isInterface() method to separate classes and interfaces.

Use Modifier.isAbstract( getClass().getModifiers() ); to find out if the class is abstract or not.

+15
source

You can try this

 cls.getModifiers() & Modifier.ABSTRACT == 0 && !cls.isInterface() 

It also makes sense to check if the class has a no-args constructor

+3
source

Source: https://habr.com/ru/post/955495/


All Articles