Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get only instantiable classes with reflections [duplicate]

I am using the reflections package to get a set of classes that implement a certain interface. This set will be used as a list of possible command line options. My problem is that I only want to get instantiable classes, but right now get both instantiable and non-instantiable classes (e.g. 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 to filter out the abstract classes?

like image 611
halfdan Avatar asked Oct 08 '13 13:10

halfdan


2 Answers

Use the isInterface() method to differentiate between classes and interfaces.

Use Modifier.isAbstract( getClass().getModifiers() ); to tell whether the class is abstract or not.

like image 164
Adam Arold Avatar answered Nov 15 '22 12:11

Adam Arold


You can try this

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

besides it makes sense to check if the class has a no-args constructor

like image 20
Evgeniy Dorofeev Avatar answered Nov 15 '22 14:11

Evgeniy Dorofeev