有条件地调用构造函数

时间:2018-01-30 15:43:44

标签: java constructor instanceof constructor-overloading

我的情况类似于this

如果我还想有条件地调用构造函数怎么办? (虽然他们说创建单独的类是可以建议的)

需求结构:

超级课程

Button btnStart = new Button();
btnStart.Click += btnStart_Click;  // This adds your event hander code to the click event

Controls.Add(btnStart);

派生类:

 public class Super
    {
        public Super(DTO1 dto1Object){
               this.dto1Object = dto1Object;     
          }

        public Super(DTO2 dto2Object)){
               this.dto2Object = dto2Object;     
          }
    }

我该如何实施?

修改

根据以下建议以这种方式实施:

超级课程

 public class Derived extends Super
    {
        public Derived(Object obj)
        {
           //some_condition to check if passed object obj is dto1Object                 
           //do something with dto1Object

           //some_condition to check if passed object is dto2Object                               
           //do something with dto2Object


        }
    }

派生类:

 public class Super
    {
        protected static DTO1 dto1Obj;
        protected static DTO2 dto2Obj;

        public Super(DTO1 dto1Object){
               this.dto1Object = dto1Object;     
          }

        public Super(DTO2 dto2Object)){
               this.dto2Object = dto2Object;     
          }
    }

EDIT2:

根据以下建议,这是使用 public class Derived extends Super { public Derived(DTO1 dto1Object){ super(dto1Object); } public Derived(DTO2 dto2Object){ super(dto2Object); } public static Derived create(Object obj) { if (obj.equals(dto1Obj) { return new Derived((DTO1) obj); } if (obj.equals(dto2Obj) { return new Derived((DTO2) obj); } // ... private String Function(String str){ if(create(dto1Obj).equals(dto1Obj) { //do something } else if(create(dto2Obj).equals(dto2Obj)){ //do something else } return str; } } } 的正确方法吗?

instanceof

显示以下错误:

if (create(dto1Obj) instanceof DTO1) {
          //something
        }
        else if(create(dto2Obj) instanceof DTO2) {
          //something else
        }

1 个答案:

答案 0 :(得分:2)

你不能在构造函数中,因为super(...)必须是第一个语句。

我能想到的唯一方法是使用静态工厂方法,并调用构造函数的特定于类的重载:

public class Derived extends Super
{
    private Derived(DTO1 dto1Object){ super(dto1Object); }
    private Derived(DTO2 dto2Object){ super(dto2Object); }

    public static Derived create(Object obj) {
       //some_condition to check if passed object obj is dto1Object                 
       //do something with dto1Object
       if (someCondition) {
         return new Derived((DTO1) obj);
       }

       //some_condition to check if passed object is dto2Object                               
       //do something with dto2Object
       if (someOtherCondition) {
         return new Derived((DTO2) obj);
       }

       // ...?
    }
}