I would like to create an instance of a specified class using its name. My code is shown below.
I get a compiler warning. Am I doing this the right way? Is it even p
I think that the first method should look something like this:
public static T create(final String className, Class ifaceClass)
throws ClassNotFoundException {
final Class clazz = Class.forName(className).asSubclass(ifaceClass);
return create(clazz);
}
You cannot do an up-cast typecast using a type parameter ... without those pesky type-safety warnings.
By the way, if you ignore those warnings, the create method may create an instance of some class that isn't compatible with the actual type used by the caller. This is likely to lead to an unexpected ClassCastException later on; e.g. when the instance is assigned.
EDIT: @Pascal points out that we need to add a typecast to make this compile; i.e.
Class clazz = (Class) Class.forName(className).asSubclass(ifaceClass);
Unfortunately, we also need to add a @SuppressWarnings annotation.