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

廉价感情. 提交于 2019-12-11 11:22:01

问题


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?


回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/23207000/specify-which-implementation-of-java-interface-to-use-in-command-line-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!