Invoking abstract method of enum

Aron :

So, I've got an enum like so,

public enum PlanProcessor { 
    A(1){
        @Override
        void processPlan(...){
            // logicA
        }

    }, 
    B(2){
        @Override
        void processPlan(...){
            // logicB
        }

    };

    abstract void processPlan(...);

    private int code;

    public static PlanProcessor valueOf(int code) {
        for (PlanProcessor type : values()) {
            if (type.code == code) {
                return type;
            }
        }
        throw new IllegalArgumentException("No enum const " + code);
    }
}

Now in the service class,

void execute(int classId) {
    PlanProcessor p = null;
    switch(PlanProcessor.valueOf(classId)){
    case A: {
                p = PlanProcessor.A;
                break;
            }
    case B: {
                p = PlanProcessor.B;
                break;
            }
    }

    p.processPlan(...);
}

Now, everything works fine here. But I was wondering, is there a better way to invoke processPlan() for A,B,C than using a switch()?

Do let me know if you do. Thanks.

Slaw :

Your valueOf(int) method already returns an instance of PlanProcessor. You then switch on the returned constant where each case assigns p the... same constant as defined for the case. In other words, your switch statement is completely redundant. This may be easier to see if you extract the selector expression for the switch statement into a variable:

void execute(int classId) {
  PlanProcessor p = null;

  PlanProcessor temp = PlanProcessor.valueOf(classId);
  switch (temp) {
    case A: // case for PlanProcessor.A
      p = PlanProcessor.A; // equivalent to "p = temp"
      break;
    case B: // case for PlanProcessor.B
      p = PlanProcessor.B; // equivalent to "p = temp"
      break;
  }

  p.processPlan(...);
}

The above can be simplified to:

void execute(int classId) {
  PlanProcessor p = PlanProcessor.valueOf(classId);
  p.processPlan(...);
}

Which, if you only need the PlanProcessor constant to invoke processPlan, can be simplified even further:

void execute(int classId) {
  PlanProcessor.valueOf(classId).processPlan(...);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393728&siteId=1