Java – enums | lookup enum by value

 

Overview

This article explains how Java enums work and different ways to lookup Enums based on their values. It also explains the performance of different approaches of java enum reverse lookup and performance of valueof method. 

Java Enums

Enums were introduced as part of JDK5 version to enable programmers to create a set of constants with below characteristics-

  • Enum types can’t be declared as abstract and final, it results in compilation error.
  • Enum types can’t be explicitally instantiated. Nested Enum types are implicitally static. 
  • All enums defined in the code implicitally extends from abstract class Enum.java provided in JDK. 
  • Two Enum constants can be compared using == operator without the need to call equals method. Equals method in abstract class “Enum.java” is made final so that it can’t be overriden by the programmers.

How does Jdk ensures that programmer can’t instantiate Enum constant by all available means?

  • Clone method in abstract class Enum is made final and throws CloneNotSupported Exception.
    Snippet from Java’s Enum class-
     1 2 3
     protected final Object clone() throws CloneNotSupportedException {     throw new CloneNotSupportedException(); } 
  • Initializing Enum constants using Reflection throws exception. 
     1 2 3 4 5 6
     // enum declaration public enum EnumTest {     ONE,     TWO,     THREE; } 
     1 2 3 4 5 6 7 8 9
     public class EnumReflectionTest {      public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {          Class<?> enumTest = Class.forName("com.techoneness.utils.EnumTest");         Object object  = enumTest.newInstance();     }  } 
     Output -   Exception in thread "main" java.lang.InstantiationException: com.techoneness.utils.EnumTest     at java.lang.Class.newInstance(Class.java:364)     at com.techoneness.utils.EnumReflectionTest.main(EnumReflectionTest.java:11)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     at java.lang.reflect.Method.invoke(Method.java:606)     at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134) 

  • Serialization mechanism ensures that duplicate enums are not initialized as part of deserialization. It gives the existing Enum present in memory.

On next page we are going to see in what scenarios reverse lookup is required for enums and how to do that. 

Pages: 1 2 3

Leave a Reply

Your email address will not be published. Required fields are marked *