I have an Enum called Plugins:
public enum Plugins {
ROTATING_LINE (plugin.rotatingline.RotatingLine.class),
SNOW_SYSTEM (plugin.snow.SnowSystem.cla
Yes, you can do it using reflection. In fact, we are doing almost exactly the same within an enum in our project. It works nicely, although I am not 100% comfortable with all the direct dependencies this solution creates. It may be better to somehow use DI via e.g. Spring, however this hasn't bugged me enough to actually experiment with a solution.
If the class has a default constructor, simply call c.newInstance()
. If not, the issue is a bit more complicated - here is another post dealing with this.
Of course, once you have the objects, you need to do something with them. The standard way is to have all classes involved implement the same interface, then you can cast down the objects to that interface and call interface methods on them. (Of course, in production code, you need to catch and handle all possible runtime exceptions which might arise - such as InstantiationException
, IllegalAccessException
and ClassCastException
).