指定在命令行参数中使用的Java接口实现 [英] Specify which implementation of Java interface to use in command line argument
问题描述
假设我有一个Java接口 Blender.java
,包含各种实现 Cuisinart.java
, Oster.java
, Blendtec.java
等等。现在我想写一个这样的程序:
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();
}
}
但现在如果我想使用 Blendtec
而不是 Cuisinart
,我必须打开源代码,更改代码并重新编译。
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.
相反,我希望能够通过编写课程来指定在运行程序时动态使用哪个 Blender
我希望将name作为命令行参数。
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.
但是如何从包含类的 name 的String转到构建实际的那个类的实例?
But how can I go from a String containing the name of a class, to constructing an actual instance of that class?
推荐答案
如果你不想经历麻烦那就是Java反射,你可以编写一个简单的静态工厂方法,它接受一个String并返回相应的对象。
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
}
}
然后你就过去了在你的命令行参数中,你将拥有你需要的任何Blender。
Then you just pass in your command line argument into it and you'll have whatever Blender you need.
唯一可能的设计问题是你必须为每个类输入一行它实现了Blender,因此如果稍后添加更多类型,则必须更新该方法。
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.
这篇关于指定在命令行参数中使用的Java接口实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!