Loose connection with Class.forName ()

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 is as follows: Hello from SBI static

What should I add to my code, and Y should alsoprint the expression
Connected to SBI

Detailed explanation is much appreciated

Ps noob here

+5
source share
2 answers

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);
    }
}
+4

Class.forName() . . "Hello from SBI static" ( static { ... } - ).

"Connected to SBI", connect():

Class<? extends Bank> bankClass = (Class<? extends Bank>)Class.forName(className);
Bank bank = bankClass.newInstance();
bank.connect();
+1

All Articles