Last active
August 8, 2016 00:49
-
-
Save WesJD/1ce6a6e67f01d7628679e87c3586799a to your computer and use it in GitHub Desktop.
Dynamic instance manager with Reflections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InstanceManager<T> { | |
private final List<T> instances = new ArrayList<>(); | |
public InstanceManager(Class<T> superclass, String packageSearch) { | |
new Reflections(packageSearch).getSubTypesOf(superclass).forEach(clazz -> { | |
try { | |
instances.add(clazz.newInstance()); | |
} catch (InstantiationException | IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
}); | |
} | |
public T getByClass(Class<? extends T> clazz) { | |
return instances.stream().filter(instance -> instance.getClass().equals(clazz)).findFirst().orElse(null); | |
} | |
public Collection<T> getAll() { | |
return Collections.unmodifiableCollection(instances); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment