Google
 
Web unafbapune.blogspot.com

Saturday, January 21, 2006

 

Trivial Java Quiz

Can you name a public method in JDK1.5 that exists in a class, but cannot be found declared or defined anywhere in the class (source file) ? In other words, you can invoke the method and it will behave as expected, but the method (and even the method name) cannot be found in the source code of the class (or it's super classes or super interfaces), nor in the respective javadoc.

Warning: reading futher will reveal the answer.

Here is one answer:

It appears there are two static methods generated for every enum class:
  1. method values(), which returns the full list of enum instances of the specific Enum class; and
  2. method valueOf(String), which returns the respective enum instance with the same name as the input string.
For (2), interestingly there is also a public static method valueOf with 2 parameters defined in the source file of Enum:
// existing method in Enum
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name);
For (1), it puzzles me why there isn't also a public static method like:
// why not
public static <T extends Enum<T>> T[] values(Class<T> enumType);
The Enum javadoc doesn't even mention the 2 generated static methods, although one can see them when using auto-completion in an IDE. Seems like an oversight to me.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?