You need to create a new instance of the object (using Class#newInstance()), apply it to the type you want (in your script SBI), and then call it.
Work code:
public class LooseCouplingTest {
public static void main(String... args)throws Exception {
String className = args[0];
Class<?> clazz = Class.forName(className);
Object obj = clazz.newInstance();
SBI mySBI = (SBI) obj;
mySBI.connect();
}
}
Explanation:
Class.forName("pkg.SBI")gets the reference for the class pkg.SBIin the object clazz.- As
clazza reference to SBIcalling clazz.newInstance();coincides with the call: new SBI();. clazz.newInstance();, obj SBI.SBI, obj - Object ( newInstance()), SBI connect().
API Java Reflection:
( LooseCouplingTest SBI), API Java Reflection, connect().
:
public class LooseCouplingTest {
public static void main(String... args) throws Exception {
String className = args[0];
Class<?> clazz = Class.forName(className);
Object obj = clazz.newInstance();
java.lang.reflect.Method connect = clazz.getMethod("connect");
connect.invoke(obj);
}
}