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
In all essence that is what will happen regardless of whether you're using a third party toolkit for it or not. Casting the object will inherently be mandatory unless expecting an Object
. You can however make a routine which does that for you:
public T instantiateObject(String name, Class cls) throws Exception {
return (T) Class.forName(name).newInstance();
}
Which you can use:
AClass cls = instantiateObject("com.class.AClass", AClass.class);
But if you come this far, the String name
is actually redundant (given AClass is a concrete class). You might as well:
public T instantiateObject(Class cls) throws Exception {
return (T) Class.forName(cls.getCanonicalName()).newInstance();
}
Which you can use:
AClass cls = instantiateObject(AClass.class);