1

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?

3
  • 2
    Reflection. Or you can use a DI framework such as Spring or Guice. Commented Apr 21, 2014 at 22:20
  • Reflection is an enormous topic about which I know nothing — I'd love if somebody were to get me closer to how I would use it to solve this particular problem... Commented Apr 21, 2014 at 23:18
  • I don't have time right now to write a full answer, but I use the Reflection way of doing this all the time. My 'AuthorizationService' takes a .properties config file to map permission names to implementing classes; my 'HtmlRenderer' looks in a configured package to see if there is a class <Something>Renderer for any tag found in the input e.g. <pre> is found in input, it looks for a class PreRenderer in the package given when the 'HtmlRenderer' is instantiated. No modifying code to add a new case or if when you add a new brand of blender. Commented Apr 21, 2014 at 23:51

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You have a few ways to accomplish that:

e.g. if-else construct

Blender blender = null;
if (args[0].equals("Cuisinart")) {
   blender = new Cuisinart();
} else if (...)

where args[0] is your first command line argument.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.