我们一直在用Enum.values,但是Enum中压根就没有values这个方法。。。看一个例子
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.TreeSet;
enum Explore { HERE, THERE}
public class Reflection {
public static Set<String> analyze(Class<?> enumClass) {
System.out.println("Interfaces:");
for(Type t : enumClass.getGenericInterfaces())
System.out.println(t);
System.out.println("Base:" + enumClass.getSimpleName());
System.out.println("Methods:");
Set<String> methods = new TreeSet<String>();
for(Method m : enumClass.getMethods())
methods.add(m.getName());
System.out.println(methods);
return methods;
}
public static void main(String[] args) throws IOException {
Set<String> exploreMetheds = analyze(Explore.class);
Set<String> enumMethods = analyze(Enum.class);
System.out.println("Explore.containsAll(Enum)? : " + exploreMetheds.containsAll(enumMethods));
System.out.println("Explore.removeAll(Enum)");
exploreMetheds.removeAll(enumMethods);
System.out.println(exploreMetheds);
}
}
输出
Interfaces:
Base:Explore
Methods:
[compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, values, wait]
Interfaces:
java.lang.Comparable<E>
interface java.io.Serializable
Base:Enum
Methods:
[compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, wait]
Explore.containsAll(Enum)? : true
Explore.removeAll(Enum)
[values]
从结果来看,Explore中包含Enum中的所有方法和接口,而且Explore的Base是Enum。
代码中把方法和接口的名字用Set集合存储了一下,然后用removeAll()去掉Explore中Enum部分。最后剩下了values
这也符合我们的要求,Enum中没有values方法,但Explore中有,但是我们也没有创建它,只有一种可能由编辑器自动创建的。。。
看一下javap命令结果查看class对应的字节码
javap Explore.class
Compiled from "Reflection.java"
final class enumerated.Explore extends java.lang.Enum<enumerated.Explore> {
public static final enumerated.Explore HERE;
public static final enumerated.Explore THERE;
static {};
public static enumerated.Explore[] values();
public static enumerated.Explore valueOf(java.lang.String);
}
还可以发现编辑器将Explore它前面的修饰符是class 所以它就是类。但是还有final修饰,所以它不能被继承
values()的神秘之处