Search code examples
javaclassinterfacefactoryhardcode

Requesting item from Factory without hard-coding every case


I have an interface called Command:

public interface Command {
// irrelevant code
}

And about 15 classes that implement this interface:

public class Comm_A implements Command {
// irrelevant code
}

public class Comm_B implements Command {...}
....
public class Comm_XZ implements Command {...}

And the factory which should take a String and return an instance of the corresponding command:

public class CommandFactory {
    public static Command getCommand(String s) {
        if (s.equals("Comm_A")) return new Comm_A();
        else ... // each particular case
    }
}

Consider that I want to be able to add new Commands without changing the factory code.

Can I make it to automatically try and create the corresponding instance WITHOUT hard-coding each "Comm_A"..."Comm_XZ" case and WITHOUT using java.lang.reflect?


Solution

  • generate the fully qualified name (package.class) and call

    Class<?> myClass = Class.forName(className);

    Then call

    myClass.newInstance();