Search code examples
javainterfacecommand-line-argumentsclassname

Specify which implementation of Java interface to use in command line argument


Say I have a Java interface Blender.java with various implementations Cuisinart.java, Oster.java, Blendtec.java, etc. Now I want to write a program like so:

public class Blendifier {
    // ...
    public static void main(String... args) {
        Blender blender = new Cuisinart();
        blender.blend();
    }
}

But now if I want to use the Blendtec instead of the Cuisinart, I have to open up the source, change the code, and recompile.

Instead, I'd like to be able to specify which Blender to use on the fly when I run the program, by writing the class name I want as a command line argument.

But how can I go from a String containing the name of a class, to constructing an actual instance of that class?


Solution

  • If you don't want to go through the trouble that is Java reflection, you can write a simple static factory method that takes a String and returns the appropriate object.

    public static Blender createBlender(String type){
        switch(type){
        case "Cuisinart": return new Cuisinart();
        case "Oster": return new Oster();
        //etc
        }
    }
    

    Then you just pass in your command line argument into it and you'll have whatever Blender you need.

    The only possible design issue is that you would have to type out a line for every class that implements Blender, so you'd have to update the method if you added more types later.