Java中的枚举开关

时间:2015-06-03 06:21:10

标签: arrays list for-loop enums switch-statement

我有这个Java类,我正在编写应用覆盖的代码。我想知道如果使用ENUM是合适的,或者我是否需要使用开关盒,我该如何使用它?另外,我有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. 为了工作的优惠,我需要使用由客户和其他人发布的格式的时间表,而这些时间段是由客户提供的分钟数。

1 个答案:

答案 0 :(得分:2)

通常,使用枚举是合适的,特别是如果您有一组已定义的可能类型。

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

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();
}