你好,我是java的新手,我想根据一个字符串条件创建一个变量,该变量将是不同类的对象。我不确定该怎么做。
这就是我要解释的内容
public class Foo {
Object obj; // I want this variable to be dynamic based on the condition in the constructor
public Foo(String str){ // Constructor
if(str.equals("bar")){
this.obj = new Bar();
}
else{
this.obj = new Baz();
}
}
我要这样,因为稍后我将使用此obj变量来调用Bar或Baz中的方法,这两种方法都实现相同名称但不同代码的方法。
答案 0 :(得分:1)
请检查此Java代码,您将了解如何使用接口来解决此问题
%Y
答案 1 :(得分:0)
听起来像策略模式,这是一个粗略的实现:
public class Foo {
Map<String, Common> strategyPattern = new HashMap<>();
private Common obj;
{
// set this up how you want, this is a static code block common to all classes
// if you're using spring you can autowire these
// Bar and Baz both implement Common interface
strategyPattern.put("bar", new Bar());
strategyPattern.put("bar", new Baz());
}
public Foo(String str) { // Constructor
this.obj = strategyPattern.get(str);
}
}
答案 2 :(得分:0)
最好的方法是创建接口而不是对象。 假定TestInterface是具有与Bar和Buz中相同方法的接口。
界面TestInterface {
100.0 * (id / Pennding Requests) AS PERCENTAGE