Creating and using a class by name requires some preconditions:
- Full name of the class must be used, including package name.
- You need to know the parameters of the constructor. Usually the no-arguments constructor is used for a such use case.
- (Optional) You need an interface this class must implement which declares the method "run" (or any other methods you want to use).
An example with a subclass of Runnable
:
String className = "some.classname.comes.from.Client";
Class<Runnable> clazz = (Class<Runnable>) Class.forName(className);
Runnable instance = clazz.getConstructor().newInstance();
instance.run();
If you don't have a common interface, you can invoke the method using reflection:
Class<Object> clazz = (Class<Object>) Class.forName(className);
Object instance = clazz.getConstructor().newInstance();
clazz.getMethod("run").invoke(instance);
or using method with parameters:
Integer p1 = 1;
int p2 = 2;
clazz.getMethod("methodWithParams", Integer.class, Integer.TYPE).invoke(instance, p1, p2);