interface Bank {
void connect();
}
class SBI implements Bank {
static{
System.out.println("Hello from SBI static");
}
public void connect() {
System.out.println("Connected to SBI");
}
}
class LooseCouplingTest {
public static void main(String... args)throws Exception {
String className = args[0];
Class.forName(className);
}
}
The output for the above code appears to be
Hello from SBI static
What should I add to my code and Y to also
print the statement
Connected to SBI
In detail explanation is much appreciated
P.S. Noob here
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.clazz
holds a reference to SBI
, calling clazz.newInstance();
is the same as calling: new SBI();
.clazz.newInstance();
, then, the variable obj
will receive a SBI
instance.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()
.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);
}
}