11

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?

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
halfdan
  • 33,545
  • 8
  • 78
  • 87
  • See http://stackoverflow.com/questions/1072890/how-can-i-determine-whether-a-java-class-is-abstract-by-reflection – rusmus Oct 08 '13 at 13:47
  • @rusmus, I specifically asked for non-instantiable classes and abstract classes are only one example of that. Granted, the question you linked covers abstract classes pretty well, but I didn't know how to check for interfaces. – halfdan Oct 08 '13 at 14:03
  • This is not a duplicate question. It asked about Reflections (and gave a link), not reflection. – whistling_marmot May 21 '21 at 13:17

2 Answers2

25

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

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

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
8

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    Thanks! Would love to accept your answer as well, but picked Adams simply because I prefer the isAbstract method. – halfdan Oct 08 '13 at 14:31