- values()是编译器为enum类添加的静态方法;
- valueOf()也是编译器为enum类添加的静态方法,和Enum类中的valueOf()方法不是一个,Enum类中的valueOf()方法有两个参数;
- enum类的基类是Enum,Enum的基类是Object;
- enum类比Enum类的多出一个values()方法,编译器给加的嘛;
package chapter19._4;
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("----- Analyze " + enumClass + " -----");
System.out.print("Interfaces: ");
for (Type t : enumClass.getGenericInterfaces())
System.out.print(t + " ");
System.out.println();
System.out.println("Base: " + enumClass.getSuperclass());
System.out.println("Method: ");
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) {
Set<String> exploreMethods = analyze(Explore.class);
Set<String> enumMethods = analyze(Enum.class);
System.out.println("Explore.containsAll(Enum)? " + exploreMethods.containsAll(enumMethods));
System.out.print("Explore.removeAll(Enum)?");
exploreMethods.removeAll(enumMethods);
System.out.println(exploreMethods);
}
}
输出:
----- Analyze class chapter19._4.Explore -----
Interfaces:
Base: class java.lang.Enum
Method:
[compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, values, wait]
----- Analyze class java.lang.Enum -----
Interfaces: java.lang.Comparable<E> interface java.io.Serializable
Base: class java.lang.Object
Method:
[compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, wait]
Explore.containsAll(Enum)? true
Explore.removeAll(Enum)?[values]
- 把enum实例向上造型成Enum类的变量,将“窄化”enum实例,使enum实例丢失values()方法;
- 窄化过的enum实例(用Enum变量e接着)可以可以通过Class类的getEnumConstants()方法,获取“窄化”成Enum类的enum类(Search )中的所有enum实例,enum实例可以用Enum类的变量e接着;
- 对于向上造型成的e,e.getClass()还是子类Search;
package chapter19._4;
enum Search { HITHER, YON }
public class UpcastEnum {
public static void main(String[] args) {
Search[] vals = Search.values();
Enum e = Search.HITHER;
System.out.println(e.getClass());
// e.values();
for (Enum en : e.getClass().getEnumConstants()) {
System.out.println(en);
}
}
}
输出:
class chapter19._4.Search
HITHER
YON
- 对于不是Enum的Class调用getEnumConstants(),返回null;
- Integer.class完了的结果,得用Class类的变量接着;
package chapter19._4;
public class NonEnum {
public static void main(String[] args) {
Class<Integer> intClass = Integer.class;
try {
for (Object en : intClass.getEnumConstants()) {
System.out.println(en);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.NullPointerException