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 forpkg.SBI
class in theclazz
object.- As
clazz
holds a reference toSBI
, callingclazz.newInstance();
is the same as calling:new SBI();
. - After calling
clazz.newInstance();
, then, the variableobj
will receive aSBI
instance. - As you want to call a
SBI
method andobj
's type isObject
(that's thenewInstance()
method's return type) you have to cast it toSBI
and only then callconnect()
.
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);
}
}