Middle
// ... some code here? private static List<DocumentProvider> getDocumentProviders() { Reflections reflections = new Reflections(Main.class.getProtectionDomain().getCodeSource().getLocation()); Set<Class<?>> subTypes = reflections.get(SubTypes.of(DocumentProvider.class).asClass()); return subTypes.stream().map(subType -> { try { return (DocumentProvider) subType.getConstructor().newInstance(); } catch (Exception ex) { throw new RuntimeException(ex); } }).collect(Collectors.toList()); }
sobes.tech AI
Answer from AI
This code uses the Reflections library for dynamic discovery of all classes that are subclasses or implement the DocumentProvider interface.
Main steps:
- An instance of Reflections is created, initialized by obtaining the location of the current Main class.
- Using the method get(SubTypes.of(DocumentProvider.class).asClass()), a set of all classes implementing DocumentProvider is obtained.
- For each such class, a new instance is created via reflection (no-argument constructor).
- All instances are collected into a list and returned.
Thus, this method allows dynamically obtaining a list of all available implementations of DocumentProvider without explicitly enumerating classes.
Example of using Reflections:
Reflections reflections = new Reflections("com.example.providers");
Set<Class<? extends DocumentProvider>> providers = reflections.getSubTypesOf(DocumentProvider.class);
for (Class<? extends DocumentProvider> providerClass : providers) {
DocumentProvider provider = providerClass.getDeclaredConstructor().newInstance();
// use provider
}
It is important that classes have a public no-argument constructor; otherwise, creating an instance will throw an exception.