đ Bug in the JDK? A Curious Case with Enum.valueOf()
TL;DR:
Donât worry, this wonât break your app. Itâs a harmless quirk, but an interesting one I stumbled upon while preparing for the Java 21 certification.
While studying for the Java 21 Certification, I had to explore many corners of the language that I donât usually touch in day-to-day development. Itâs been an eye-opening journey â lots of learning, and plenty of hidden details that we often take for granted.
And then I ran into something⌠odd.
You probably know that Enum.valueOf()
throws an IllegalArgumentException
when the provided string doesnât match any constant in the enum. Hereâs a basic example:
enum Date {
DAY,
WEEK,
MONTH;
}
public class Main {
public static void main(String[] args) {
System.out.println(Date.valueOf("DAY")); // â
OK
System.out.println(Date.valueOf("Banana")); // â Throws IllegalArgumentException: No enum constant Date.Banana
}
}
Makes sense, right?
But hereâs where it gets weird. You can actually declare an enum
inside a method â and when you do, things behave differently.
public class Main {
public static void main(String[] args) {
enum Type {
DAY, WEEK, MONTH;
}
System.out.println(Type.valueOf("DAY")); // â
OK
System.out.println(Type.valueOf("Banana")); // â IllegalArgumentException: No enum constant null.Banana
}
}
Wait â null.Banana
? đ¤¨
𤯠Whatâs going on?
Behind the scenes, all enums in Java extend the abstract java.lang.Enum
class, and the valueOf()
method is defined as:
public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name)
This method relies on Class.getCanonicalName()
to include the enumâs full name in the error message. However, if the enum is declared inside a method, it doesnât have a canonical name, so the result is null
.
Donât believe me? Try this:
public class Main {
public static void main(String[] args) {
class A {}
System.out.println(A.class.getCanonicalName()); // Prints: null
}
}
đ§ Why does this matter?
Is this a real bug? Maybe. Is it a big deal? Probably not.
But itâs a great reminder that going deep into the language, especially while studying for certification, can expose behavior you wouldnât normally encounter.
These little discoveries are part of what makes learning fun.
PS: Donât write enums inside methods in production code. Seriously. đ
Want to see more quirky corners of the JDK? Or have you stumbled upon something strange yourself?
Drop a comment and share it, Iâd love to hear about it!