1.4 values()方法的神秘之处


枚举类型是由编译器通过继承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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值