سؤال

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?

هل كانت مفيدة؟

المحلول

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

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

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top