You have to create a new instance of the object (using Class#newInstance()
), cast it to the type you want (in your scenario SBI
), and then call it.
Working 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 a reference for pkg.SBI
class in the clazz
object.
- As
clazz
holds a reference to SBI
, calling clazz.newInstance();
is the same as calling: new SBI();
.
- After calling
clazz.newInstance();
, then, the variable obj
will receive a SBI
instance.
- As you want to call a
SBI
method and obj
's type is Object
(that's the newInstance()
method's return type) you have to cast it to SBI
and only then call connect()
.
Using Java's Reflection API:
If you wish to go even further and not even do the cast (this way LooseCouplingTest
never needs to import SBI
), you can use Java's Reflection API to invoke the connect()
method.
Here's the working code for that:
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);
}
}