How to get only the subtypes that can be instantiated for a specified base class?

40 views
Skip to first unread message

mari...@gmail.com

unread,
Apr 13, 2015, 12:52:15 PM4/13/15
to google-code...@googlegroups.com
I needed to retrieve only the concrete classes for a specific class and since I haven't found a better method I tweaked one myself :

Reflections reflections = new Reflections(packageName);
Iterable<String> exampleSubclasses = reflections.getStore().getAll(SubTypesScanner.class.getSimpleName(), Arrays
.asList(Example.class.getName()));

Set<Class<? extends Example>> result = new LinkedHashSet<Class<? extends Example>>();
for (String className : exampleSubclasses) {
Class<? extends Example> clazz = (Class<? extends Example>) ReflectionUtils.forName(className);
boolean canBeInstantiated = !(clazz.isInterface() || clazz.isEnum() || Modifier.isAbstract(clazz
.getModifiers()));
if (canBeInstantiated) result.add(clazz);
}



Would there be a more elegant fashion to handle this case with the reflections library?

stephen....@gmail.com

unread,
Apr 30, 2015, 9:13:53 AM4/30/15
to google-code...@googlegroups.com, mari...@gmail.com
My solution for this:
private Set<Class<? extends JaxbContextPath>> findJaxbFactoryClasses() {
final Reflections reflections = new Reflections("com.acme.foo");
Set<Class<? extends JaxbContextPath>> classes = reflections.getSubTypesOf(JaxbContextPath.class);
//noinspection unchecked
classes = ReflectionUtils.getAll(classes, IS_CONCRETE_CLASS);
return classes;
}
and
private static final Predicate<? super Class<? extends JaxbContextPath>> IS_CONCRETE_CLASS = new Predicate<Class<? extends JaxbContextPath>>() {
@Override
public boolean apply(final Class<? extends JaxbContextPath> input) {
return !input.isInterface() && !Modifier.isAbstract(input.getModifiers());
}
};

but I still wonder, if there's a nicer way.
Reply all
Reply to author
Forward
0 new messages