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

Razvan picture Razvan · Aug 11, 2012 · Viewed 16.9k times · Source

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 ?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Aug 11, 2012

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);