Where does the Enum.valueOf(String) method come from?

倾然丶 夕夏残阳落幕 提交于 2019-11-27 13:46:52

问题


In Java SE 7 (and most probably in previous versions) the Enum class is declared like this:

 public abstract class Enum<E extends Enum<E>>
 extends Object
 implements Comparable<E>, Serializable

The Enum class has a static method with this signature:

  T static<T extends Enum<T>> valueOf(Class<T> enumType, String name) 

But there is no static method : valueOf(String) defined in the Enum class nor upwards in the hierarchy Enum belongs to.

The question is where does valueOf(String) come from ? Is it a feature of the language, i.e. a feature built in the compiler ?


回答1:


This method is implicitly defined by the compiler.

From the documentation:

Note that for a particular enum type T, the implicitly declared public static T valueOf(String) method on that enum may be used instead of this method to map from a name to the corresponding enum constant. All the constants of an enum type can be obtained by calling the implicit public static T[] values() method of that type.

From the Java Language Specification, section 8.9.2:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static 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);



回答2:


I think it must be a feature of the language. For one, to create an enum by making one and it does not need to extend Enum:

public enum myEnum { red, blue, green }

That alone, is a language feature or else you would need to do this:

public class  MyEnum extends Enum { ..... }

Secondly, the method, Enum.valueOf(Class<T> enumType, String name), must be produced by the compiler when you you use myEnum.valueOf(String name).

That is what would seem possible given that the new Enum is as much a language feature as it is a class to extend.



来源:https://stackoverflow.com/questions/11914792/where-does-the-enum-valueofstring-method-come-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!