编辑器自己添加方法-枚举类型

来源:互联网 发布:数据库建设规划 编辑:程序博客网 时间:2024/06/01 09:00

我们一直在用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);}}


这段代码的功能就是通过反射找到Explore类中的所有接口和方法,再和enum中的接口和方法进行对比

输出

Interfaces:Base:ExploreMethods:[compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, values, wait]Interfaces:java.lang.Comparable<E>interface java.io.SerializableBase:EnumMethods:[compareTo, equals, getClass, getDeclaringClass, hashCode, name, notify, notifyAll, ordinal, toString, valueOf, wait]Explore.containsAll(Enum)? : trueExplore.removeAll(Enum)[values]
从结果来看,Explore中包含Enum中的所有方法和接口,而且Explore的Base是Enum。

代码中把方法和接口的名字用Set集合存储了一下,然后用removeAll()去掉Explore中Enum部分。最后剩下了values

这也符合我们的要求,Enum中没有values方法,但Explore中有,但是我们也没有创建它,只有一种可能由编辑器自动创建的。。。


看一下javap命令结果查看class对应的字节码

javap Explore.classCompiled 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);}


从这里可以看见,在创建Explor的过程中,编辑器添加了values() 和valueOf(String)方法(这个和Enum中自带的valueOf不一样,它有参数),还有一个静态块


还可以发现编辑器将Explore它前面的修饰符是class 所以它就是类。但是还有final修饰,所以它不能被继承

values()的神秘之处

0 0
原创粉丝点击