Skip to content

Instantly share code, notes, and snippets.

@pavelfomin
Last active August 30, 2023 21:30
Show Gist options
  • Save pavelfomin/3de31df5d2a7e58cc2df64e437b5f752 to your computer and use it in GitHub Desktop.
Save pavelfomin/3de31df5d2a7e58cc2df64e437b5f752 to your computer and use it in GitHub Desktop.
Get jar locations of all classes extending a given class
import org.reflections.Reflections;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.net.URL;
import java.util.Set;
public class ClassUtil {
public <T> MultiValueMap<String, Class<? extends T>> getSubTypeLocationsOf(final String prefix, final Class<T> type) {
MultiValueMap<String, Class<? extends T>> locations = new LinkedMultiValueMap<>();
Reflections reflections = new Reflections(prefix);
Set<Class<? extends T>> modules = reflections.getSubTypesOf(type);
modules.stream().forEach(c -> {
URL resource = c.getResource('/' + c.getName().replace('.', '/') + ".class");
String location = getResourceLocation(resource);
locations.add(location, c);
}
);
return locations;
}
protected String getResourceLocation(URL resource) {
String withoutClass = resource.toString().replaceAll("(.*)(\\!.*class)", "$1");
String afterLastSlash = withoutClass.replaceAll("(.*\\/)(.*)", "$2");
return afterLastSlash;
}
}
MultiValueMap<String, Class<? extends SpecificRecord>> locations =
classUtil.getSubTypeLocationsOf("com.droidablebee", SpecificRecord.class);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment