I want to instantiate a class by the value of a String. I found several tutorials that show several methods for doing this. The class MUST inherit from a certain interface, ImplementMe
which has a special method called runMe()
. So here's what I tried:
ImplmentMe a =
(ImplementMe) ImplementMe.class
.getClassLoader()
.loadClass("my.package.IImplementedYou")
.newInstance();
a.runMe();
It works, but it's so ugly. I at least expected not needing a cast. Please tell me there is a better way.
Object
toImplementMe
.ImplementMe.class.getClassLoader()
, it would take the hint that the class must inherit fromImplementMe
..oh well.Class
has aasSubclass
method. So...loadClass(...).asSubclass(ImplementMe.class).newInstance()
will return anImplementMe
instance (if it succeeds).