解决问题: 官方解答枚举Enum的values(),valueOf(String name)是如何产生的?

     我看了网上很多说法,但是多数给出的结论都不清不楚,有更多的还是解释错误。经过查找资料得到了权威结果,与大家分享一下,避免被错误答案误导。

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9

上方链接是The Java Language Specification Java SE 8 Edition(ava语言规范Java SE 8版本),在枚举章节上有提到values(),valueOf()方法的由来。

8.9.3. Enum Members
The members of an enum type E are all of the following:

	Members declared in the body of the declaration of E.
	Members inherited from Enum<E>.
	For each enum constant c declared in the body of the declaration of E, E has an implicitly declared public static final field of type E that has the same name as c. The field has a variable initializer consisting of c, and is annotated by the same annotations as c.
	These fields are implicitly declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the body of the declaration of E.
	An enum constant is said to be created when the corresponding implicitly declared field is initialized.
The following implicitly declared methods:		//以下隐式声明的方法:

   /**
	* Returns an array containing the constants of this enum 
	* type, in the order they're declared.  This method may be
	* used to iterate over the constants as follows:
	*
	*    for(E c : E.values())
	*        System.out.println(c);
	*
	* @return an array containing the constants of this enum 
	* type, in the order they're declared
	*/
	public static E[] values();

    /**
	* Returns the enum constant of this type with the specified
	* name.
	* The string must match exactly an identifier used to declare
	* an enum constant in this type.  (Extraneous whitespace 
	* characters are not permitted.)
	* 
	* @return the enum constant with the specified name
	* @throws IllegalArgumentException if this enum type has no
	* constant with the specified name
	*/
	public static E valueOf(String name);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值