使用场景
1.类的对象有限、确定
2.当需要**一组常量**时,可以使用枚举类
如何定义枚举类
jdk5.0以前,自定义枚举类
jdk5.0以后,使用 enum 关键定义
自定义枚举
/**
* 自定义枚举类,模拟 jdk5.0 之前
*/
public class Season {
// private final 修饰属性
private final String name;
private final int value;
//私有化构造
private Season(String name, int value) {
this.value = value;
this.name = name;
}
//创建内部对象
public static final Season SPRING = new Season("spring", 1);
public static final Season SUMMER = new Season("summer", 2);
public static final Season AUTUMN = new Season("autumn", 3);
public static final Season WINTER = new Season("winter", 4);
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", value=" + value +
'}';
}
}
使用 enum 定义枚举
/**
* 自定义枚举类,jdk5.0以后
*/
public enum Period {
//创建对象要放在 定义 的开头
//直接定义枚举类的对象,使用逗号分隔,分号结束
SPRING("spring", 1),
SUMMER("summer", 2),
AUTUMN("autumn", 3),
WINTER("winter", 4);
//定义属性
private final String name;
private final int value;
//私有化构造
private Period(String name, int value) {
this.value = value;
this.name = name;
}
}
测试 自定义枚举
@SpringBootTest
public class TestEnumDemo {
@Test
public void doTest01() {
System.out.println(Season.SPRING); //Season{name='spring', value=1}
System.out.println(Season.SUMMER); //Season{name='summer', value=2}
System.out.println(Season.AUTUMN); //Season{name='autumn', value=3}
System.out.println(Season.WINTER); //Season{name='winter', value=4}
}
@Test
public void doTest02() {
System.out.println(Period.SPRING); //SPRING
System.out.println(Period.SUMMER); //SUMMER
System.out.println(Period.AUTUMN); //AUTUMN
System.out.println(Period.WINTER); //WINTER
}
@Test
public void doTest03() {
System.out.println(Period.class.getSuperclass()); //class java.lang.Enum
}
}
Enum 的常用方法
/**
* 常用方法
* 1. values()
* 获取枚举类的所有对象,以数组返回
* 2. valueOf(String s)
* 获取字符串对应的枚举对象,不能对应时报异常
* 3. toString()
* 默认就已重写,返回对象自己
*/
@Test
public void commonMethods() {
Period[] values = Period.values();
for (Period p : values) {
System.out.println(p);
}
// 常用方法 valueOf(o)
Period value1 = Period.valueOf("SPRING");
System.out.println(value1); //直接输出 枚举,等于调用 toString() 方法
Period value2 = Period.valueOf("1");
System.out.println(value2);
}
最简单的 枚举 定义
没有属性,就不要定义了,也不用定义构造方法
public enum FourSeasons {
SPRING,
SUMMER,
AUTUMN,
WINTER;
}
@Test
public void simpleEst() {
System.out.println(FourSeasons.SPRING); //SPRING
}
枚举使用实例
Spring 事务的传播机制、隔离级别
//传播行为
public enum Propagation {
REQUIRED(0),
SUPPORTS(1),
MANDATORY(2),
REQUIRES_NEW(3),
NOT_SUPPORTED(4),
NEVER(5),
NESTED(6);
private final int value;
Propagation(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
//隔离级别
public enum Isolation {
DEFAULT(-1),
READ_UNCOMMITTED(1),
READ_COMMITTED(2),
REPEATABLE_READ(4),
SERIALIZABLE(8);
private final int value;
Isolation(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
打印输出 enum 对象
@SpringBootTest
public class TestEnumExampleDemo {
@Test
public void doTest() {
System.out.println(Propagation.REQUIRED); //REQUIRED
System.out.println(Isolation.DEFAULT); //DEFAULT
System.out.println(Isolation.READ_COMMITTED); //READ_COMMITTED
}
}
枚举的定义
rt.jar java.lang.Enum
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {
private final String name;
public final String name() {
return name;
}
private final int ordinal;
public final int ordinal() {
return ordinal;
}
protected Enum(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}
public String toString() {
return name;
}
public final boolean equals(Object other) {
return this==other;
}
public final int hashCode() {
return super.hashCode();
}
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public final int compareTo(E o) {
Enum<?> other = (Enum<?>)o;
Enum<E> self = this;
if (self.getClass() != other.getClass() && // optimization
self.getDeclaringClass() != other.getDeclaringClass())
throw new ClassCastException();
return self.ordinal - other.ordinal;
}
@SuppressWarnings("unchecked")
public final Class<E> getDeclaringClass() {
Class<?> clazz = getClass();
Class<?> zuper = clazz.getSuperclass();
return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
}
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum constant " + enumType.getCanonicalName() + "." + name);
}
protected final void finalize() { }
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new InvalidObjectException("can't deserialize enum");
}
private void readObjectNoData() throws ObjectStreamException {
throw new InvalidObjectException("can't deserialize enum");
}
}
框架中定义的枚举
package org.springframework.web.bind.annotation;
/**
* Java 5 enumeration of HTTP request methods. Intended for use
* with the {@link RequestMapping#method()} attribute of the
* {@link RequestMapping} annotation.
*
* <p>Note that, by default, {@link org.springframework.web.servlet.DispatcherServlet}
* supports GET, HEAD, POST, PUT, PATCH and DELETE only. DispatcherServlet will
* process TRACE and OPTIONS with the default HttpServlet behavior unless
* explicitly told to dispatch those request types as well: Check out
* the "dispatchOptionsRequest" and "dispatchTraceRequest" properties,
* switching them to "true" if necessary.
*
* @author Juergen Hoeller
* @since 2.5
* @see RequestMapping
* @see org.springframework.web.servlet.DispatcherServlet#setDispatchOptionsRequest
* @see org.springframework.web.servlet.DispatcherServlet#setDispatchTraceRequest
*/
public enum RequestMethod {
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}