Skip to content

Instantly share code, notes, and snippets.

@benchi99
Last active June 16, 2020 07:01
Show Gist options
  • Select an option

  • Save benchi99/69ff47fb082c49b8e970575abfb613f9 to your computer and use it in GitHub Desktop.

Select an option

Save benchi99/69ff47fb082c49b8e970575abfb613f9 to your computer and use it in GitHub Desktop.
Mapping subclasses with Reflections
package com.rubenbermejo.gists
import com.reflections.Reflections
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* A class for mapping all existing subtypes of a class within a package
*
*
* @author Rubén Bermejo Romero 2020
*/
public class SubclassMapper {
private static final String CLASS_PACKAGE = "com.rubenbermejo.gists.myotherpackage";
private static final Logger logger = LoggerFactory.getLogger(SubclassMapper.class);
Reflections reflections = new Reflections(CLASS_PACKAGE);
public Map<String, MyAbstractClass> mapClasses() throws RuntimeException {
logger.debug("Looking for classes to map...");
Set<Class<? extends MyAbstractClass>> abstractClasses = reflections.getSubTypesOf(MyAbstractClass.class);
if (abstractClasses.isEmpty()) {
logger.error("No classes have been found!");
throw new RuntimeException("No classes were found!");
}
Map<String, MyAbstractClass> classMap = new HashMap<>();
for (Class<? extends MyAbstractClass> abstractClass : abstractClasses) {
try {
logger.debug("Attempting to make instance of " + abstractClass.getName());
MyAbstractClass classInstance = makeInstance(abstractClass);
classMap.put(classInstance.getClass().getName(), classInstance);
logger.debug(classInstance.getName() + " has been instantiated and mapped!");
} catch (NoSuchMethodException |
InstantiationException |
IllegalAccessException |
InvocationTargetException e) {
logger.error("Could not instantiate class - " + e.toString());
throw new RuntimeException("Error while instantiating classes");
}
}
logger.info(classMap.size() + " class(es) were mapped!");
return classMap;
}
private MyAbstractClass makeInstance(Class<? extends MyAbstractClass> abstractClass) throws NoSuchMethodException,
InstantiationException, InvocationTargetException, IllegalAccessException {
Constructor<?> classConstructor = abstractClass.getConstructor();
return (MyAbstractClass) classConstructor.newInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment