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

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


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


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

values()的神秘之处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值