- 例子:
![](https://img.haomeiwen.com/i734456/cc71578758dd8c20.png)
- 枚举类中包含两个枚举元素:PUBLIC, PRIVATE
- 在main方法中调用valueOf方法,结果分别是true,true,false
源码解析
- 主体思路:是将枚举的元素通过反射(method)转化为一个key和value都是枚举元素的HashMap<String, T>,例如上面案例中的HashMap的数据为:
![](https://img.haomeiwen.com/i734456/5d3018dd28c59562.png)
- valueOf方法调用
enumType.enumConstantDirectory()
方法
image.png
-
调用Class类的
getEnumConstantsShared
方法
image.png
-
先通过个getMehotd方法获取到Method
-
然后调用invoke方法获取到
PUBLIC
和PRIVATE
![](https://img.haomeiwen.com/i734456/82dac0d0b8b636fa.png)
总结:
- 反射的知识点可以看这篇文章:http://www.jianshu.com/p/2bc886dd7a8a
- 提供了将枚举元素转化为Map的一种思路
网友评论