好久不写博客了,回忆回忆一下Java枚举
> enum 关键字来定义,各个常量使用逗号 , 来分割
package cn.tina.enums;
import java.util.Arrays;
/**
* 根据不同日期查询数据拼接SQL
*
* @author Tina
* @version 1.0
* @since 2022/1/24 22:45
**/
public enum Growth {
TODAY("today", "and TO_CHAR(LOGIN_TIME,'YYYY-MM-DD')=TO_CHAR(SYSDATE,'YYYY-MM-DD')"),
YESTERDAY("yesterday", "and TO_CHAR(LOGIN_TIME,'YYYY-MM-DD')=TO_CHAR(SYSDATE-1,'YYYY-MM-DD')"),
THISWEEK("thisWeek", "and LOGIN_TIME >= TRUNC(NEXT_DAY(SYSDATE-8,1)+1) AND LOGIN_TIME < TRUNC(NEXT_DAY(SYSDATE-8,1)+7)+1"),
LASTWEEK("lastWeek", "and LOGIN_TIME >= TRUNC(NEXT_DAY(SYSDATE-8,1)-6) AND LOGIN_TIME < TRUNC(NEXT_DAY(SYSDATE-8,1)+1)"),
THISMONTH("thisMonth", "and TO_CHAR(LOGIN_TIME,'YYYY-MM')=TO_CHAR(SYSDATE,'YYYY-MM')"),
LASTMONTH("lastMonth", "and TO_CHAR(LOGIN_TIME,'YYYY-MM')=TO_CHAR(ADD_MONTHS(SYSDATE,-1),'YYYY-MM')"),
UNKNOWN("error", "and 1=1"),
ALL("all", "and 1=1");
private String key;
private String sql;
Growth(String key, String sql) {
this.key = key;
this.sql = sql;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
/**
* 根据Key得到枚举的Value
* 普通for循环遍历,比较判断
*
* @param key
* @return
*/
public static Growth getEnumType(String key) {
Growth[] Growths = Growth.values();
for (int i = 0; i < Growths.length; i++) {
if (Growths[i].getKey().equals(key)) {
return Growths[i];
}
}
return Growth.UNKNOWN;
}
/**
* 根据Key得到枚举的Value
* 增强for循环遍历,比较判断
*
* @param key
* @return
*/
public static Growth getEnumType1(String key) {
Growth[] Growths = Growth.values();
for (Growth Growth : Growths) {
if (Growth.getKey().equals(key)) {
return Growth;
}
}
return Growth.UNKNOWN;
}
/**
* 根据Key得到枚举的Value
* Lambda表达式,比较判断(JDK 1.8)
*
* @param key
* @return
*/
public static Growth getEnumType2(String key) {
Growth[] Growths = Growth.values();
Growth result = Arrays.asList(Growths).stream()
.filter(Growth -> Growth.getKey().equals(key))
.findFirst().orElse(Growth.UNKNOWN);
return result;
}
/**
* 根据Key得到枚举的Value
* Lambda表达式,比较判断(JDK 1.8)
*
* @param key
* @return
*/
public static Growth getEnumType3(String key) {
return Arrays.asList(Growth.values()).stream()
.filter(Growth -> Growth.getKey().equals(key))
.findFirst().orElse(Growth.UNKNOWN);
}
@Override
public String toString() {
return "Growth{" +
"key='" + key + '\'' +
", sql='" + sql + '\'' +
'}';
}
}
注意一下:toString 需要重写