Java 中的枚举开关

Enum switch in Java

我有这个 Java class,我正在其中编写应用覆盖的代码。我想知道使用 ENUM 是否合适或者我是否需要使用 switch case,我该如何使用它?此外,我有一个 for 循环,我需要将其用作每个覆盖类型的公共代码块。除此之外,我确实有几个单独的字段需要为每种覆盖类型进行编码。

    public class EWFMService
    {
    private WorkbrainSystemAccessService wsa = new WorkbrainSystemAccessService();

private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(EWFMService.class);
private final static String ovrCalcGrp = "ovrCalcGrp";
private DBConnection conn = null;
private int empId;
private Date ovrDate;
private String ovrTime;
private String ovrAction;



public List<EWFMServiceData> getProcessEWFMOverrides(String userName, String password, List<EWFMServiceInputData> inputData)
throws WSApplicationException{      

    logger.debug("EWFM Service");       
    wsa.logOn(userName, password);    

    List<EWFMServiceData> returnList = new ArrayList<EWFMServiceData> ();
    logger.debug("userName = " + userName);

    DBConnection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try{
        conn = new DBConnection(ConnectionManager.getConnection());

    for (int i = 0; i < inputData.size(); i++) 
    {

在这里,我想从数据库中检索 emp_id,将值存储在一个变量中,并能够在我的程序的其余部分中使用该变量。我该怎么做?要检索 emp_id,我使用以下查询。

        conn = new DBConnection(ConnectionManager.getConnection());
        String sql = "SELECT EMP_ID FROM EMPLOYEE_HISTORY"
                + " WHERE EMP_VAL2 = **This is where I want to use the variable in which the values of emp_id will be stored. There can be more than 100 emp_ids**"
                + " AND SYSDATE BETWEEN EMPHIST_START_DATE AND      EMPHIST_END_DATE";


        EWFMServiceInputData inData = (EWFMServiceInputData)    inputData.get(i);
        OverrideType ot = OverrideType.getOverrideType(inData.getRecordType());
        logger.debug("override type = " + ot.toString());           
        logger.debug("inputData ["+i+"] = " + inData.toString());

       OverrideAccess oa = new OverrideAccess(conn);
        OverrideData ovr = new OverrideData();
        ovr.setOvrUdf4(inData.getReferenceId().toString());
        if (ovrAction.equals("APPLY")) {
            ovr.setOvrStatus(OverrideData.PENDING); 

这里我要确定Action。如果是 Apply,那么我需要找出 recordType。所以基本上使用 if else 语句或枚举为每个 recordType 分支出来,因为我相信 switch 不支持 Java 1.5,这正是我正在使用的。然后对于每个 recordType,我分支并编写与该 recordType 对应的适当代码。如果Action是CANCEL,那我就写下面的代码。

        } else if (ovrAction.equals("CANCEL")) {
            String sql = "SELECT * FROM OVERRIDE"
                    + " WHERE OVR_UDF4 = ?"
                    + " AND OVRTYP_ID = ?";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()); {
                ovr.assignByName(rs);
                ovr.setUpdated(false);
                ovr.setRetrieved(true);
                ovr.setOvrStatus(OverrideData.CANCEL);
                oa.save(ovr);                                   
            }
        }           
        ovr.setEmpId(empId);
        String strOvrDate = inData.getOvrStartDate();

        ovr.setOvrStartDate(DateHelper.parseDate(strOvrDate, "MM/dd/yyyy"));


        if (ovrStartTime != null) {
            ovr.setOvrStartTime(ovrTime);
        }
        Object ovrEndDate;
        if (ovrEndDate != null) {
            ovr.setOvrEndDate(ovrDate);
        }
        Object ovrEndTime;
        if (ovrEndTime!= null) {
            ovr.setOvrEndTime(ovrTime);
        }
        ovr.setOvrComment(inData.getOvrComments());
        ovr.setWbuName(inData.getWbuName());
        ovr.setWbuNameActual(inData.getWbuNameActual());
        ovr.setOvrNewValue("VAC");
        ovr.setOvrCreateDate(new Date());
        ovr.setOvrtypId(103);
        oa.insert(ovr);
        RuleEngine.runCalcGroup(conn,
                empId,
                ovrDate,
                ovrDate);   
        //COMMON BLOCK ENDS HERE
        EWFMServiceData outData = new EWFMServiceData();
        outData.setReferenceId(inData.getReferenceId());            

        String [] status = {"SUCCESS", "ERROR", "LOCKED", "EXCEPTION"};
        Random ran = new Random();
        String gen = status[ran.nextInt(status.length)];
        logger.debug("Status is"  + status );
        outData.setStatus(gen);         
        if (gen.equals("SUCCESS")){
         outData.setErrorDetails("");
        } else if (gen.equals("ERROR")) {
            outData.setErrorDetails("Usage of time code VAC is not allowed; balance is insufficient." + " error");
        } else if (gen.equals("LOCKED")) {
            outData.setErrorDetails("Timesheet cannot be edited because it is locked for payroll close." + "locked");
        } else if (gen.equals("EXCEPTION")) {
            outData.setErrorDetails("{ML}QR_INCORRECT_CONDITION_PARAMETER{/ML}Error in condition AWA Is Self Override Condition: java.lang.NullPointerException{ARGS}AWA Is Self Override Conditionjava.lang.NullPointerException{/ARGS" + "exception");
        }
        returnList.add(outData);
    } 
    }catch (Exception e){
    logger.error("Error occured",e);
    throw new WSApplicationException("Error retrieved",e);
}finally{
    SQLUtil.cleanUp(conn, ps, rs);
}

    wsa.logOff();

    logger.debug("inputData+ ");

    return returnList;

}



   // I need to know if writing enum is okay or can I just write a switch    case above in the for loop and branch each override type and declare their individual variables there? What's the best way? Can someone help me with the code?
   public enum OverrideType {
   WORKDETAIL,
   WORKPREMIUM,
   EMPLOYEESCHEDULE,
   EMPLOYEE;

   public static OverrideType getOverrideType(String recordType) {
       if(recordType == null) {
           throw new IllegalArgumentException("Record Type cannot be null");
       }
       if(recordType.equals("Work Detail")) {


           return WORKDETAIL;

       } else if (recordType.equals("Work Premium")) {
           return WORKPREMIUM;
       } else if (recordType.equals("Schedule")) {
           return EMPLOYEESCHEDULE;
       } else if (recordType.equals("Shift Pattern")) {
           return EMPLOYEE;
       } else {
           throw new IllegalArgumentException("Record Type cannot be" + recordType);
       }
   }

   } 

   }

我需要包括的其他字段如下:

  1. 对于工作细节,我需要使用客户端发送的格式的时间码。
  2. 对于 WORK PREMIUM,我需要使用客户端发送的格式的时间码,另一个字段是 MINUTES,它给出了客户端也发送的分钟数。

通常,使用枚举是合适的,尤其是当您定义了一组可能的类型时。

您还可以向枚举添加行为,这可以使您的枚举更加复杂:

public enum OverrideType {
        WORKDETAIL("Work Detail"),
        WORKPREMIUM("Work Premium"),
        EMPLOYEESCHEDULE("Schedule"),
        EMPLOYEE("Shift Pattern");

        private String identifier;

        private OverrideType(String identifier){
            this.identifier = identifier;
        }

        public static OverrideType getOverrideType(String recordType) {

            if(recordType == null) {
                throw new IllegalArgumentException("Record Type cannot be null");
            }

            for (OverrideType ot : OverrideType.values()) {
                if (recordType.equals(ot.identifier)) {
                    return ot;
                }
            }

            return null;
        }
}

以下示例展示了如何在枚举中使用接口或抽象方法定义:

public enum OverrideType implements OverrideTypeIF {
    WORKDETAIL("Work Detail") {
        public int getKey() {
            return 0;
        }
    },
    WORKPREMIUM("Work Premium") {
        public int getKey() {
            return 0;

        }
    },

    EMPLOYEESCHEDULE("Schedule") {
        public int getKey() {
            return 0;

        }
    },
    EMPLOYEE("Shift Pattern") {
        public int getKey() {
            return 0;
        }

        public void myInterfaceMethod() {
            // do type specific behavior
        }
    };

    private String identifier;

    private OverrideType(String identifier){
        this.identifier = identifier;
    }

    public abstract int getKey();

    public void myInterfaceMethod() {
        // do default behavior
    }

    public static OverrideType getOverrideType(String recordType) {

        if(recordType == null) {
            throw new IllegalArgumentException("Record Type cannot be null");
        }

        for (OverrideType ot : OverrideType.values()) {
            if (recordType.equals(ot.identifier)) {
                return ot;
            }
        }

        return null;
    }
}

public interface OverrideTypeIF {
    void myInterfaceMethod();
}