枚举类型是由编译器通过继承Enum
类来创建的。但其实Enum
类中并没有values
方法。
可以使用反射来分析一下枚举类
package www.com.cat.chapter01;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
@SuppressWarnings("all")
enum Tectosome {
QU, LUNA, LUXIYA;
}
@SuppressWarnings("all")
public class Reflection {
public static Set<String> analyze(Class<?> enumClass) {
System.out.println("Analyzing class Tectosome");
System.out.println("Interface : ");
Arrays.stream(enumClass.getGenericInterfaces()).forEach(System.out::println);
System.out.println("Base : " + enumClass.getSuperclass());
System.out.println("Methods : ");
TreeSet<String> methods = new TreeSet<>();
Arrays.stream(enumClass.getMethods()).forEach(method -> methods.add(method.getName()));
System.out.println(methods);
return methods;
}
public static void main(String[] args) throws IOException {
Set<String> tectosomeMethods = analyze(Tectosome.class);
Set<String> enumMethods = analyze(Enum.class);
System.out.println("tectosomeMethods.containsAll(enumMethods) = " + tectosomeMethods.containsAll(enumMethods));
System.out.print("tectosomeMethods.removeAll(enumMethods) = ");
tectosomeMethods.removeAll(enumMethods);
System.out.println(tectosomeMethods);
}
}
输出 :
Analyzing class Tectosome
Interface :
Base : class java.lang.Enum
Methods :
[compareTo, describeConstable, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, values, wait]
Analyzing class Tectosome
Interface :
interface java.lang.constant.Constable
java.lang.Comparable<E>
interface java.io.Serializable
Base : class java.lang.Object
Methods :
[compareTo, describeConstable, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, wait]
tectosomeMethods.containsAll(enumMethods) = true
tectosomeMethods.removeAll(enumMethods) = [values]
values
方法是由编译器添加的一个静态方法。
如果你将Tectosome
转型为Enum
,你将失去values
方法。
Enum e = Tectosome.QU;
// e.valuse(); 错误
// 但是没关系,在class类中有一个getEnumConstants可以实现同样的效果
Arrays.stream(e.getClass().getEnumConstants()).forEach(System.out::println);
输出 :
QU
LUNA
LUXIYA