Do you want to instantiate a class by name?
First of all, you need to create a Class<?> Object:
Class<?> cls = Class.forName(strClassName);
Then create an instance (note that this can cause various exceptions - access violation, ClassNotFound , no public constructor without arguments, etc.)
Object instance = cls.newInstance();
Then you can do this:
return (SomeClass) instance;
Please make sure you understand the differences between:
- Class name (approximately file name)
- Class object (essentially type information)
- Instance class (actual object of this type)
You can also give the cls object a Class<? extends SomeClass> Class<? extends SomeClass> if you want. It does not give you much. And you can insert it to:
return (SomeClass)(Class.forName(strClassName).newInstance());
Oh, but you can do type checking with the cls object before creating it. This way you only initiate it if it satisfies your API (implements the interface you want to get).
EDIT: Add another example code in the direction of reflection .
For instance:
if (cls.isInstance(request)) {
To call methods, you need to know an interface that you can use, or use reflection ( getMethod methods of the getMethod object):
Method getRequest = cls.getMethod("getRequest"); getRequest.invoke(request);
source share