Reverse Enum constants from strings and values in Java

Overview

--Sample code to get an Enum constant from a value in Java --Build the sample code with the javac command and run it with the java command --Operation check environment: macOS Catalina + Java 8 (AdoptOpenJDK 1.8.0_242-b08)

Enums are available from Java 5 (codename Tiger)

Enumeration

Tiger linguistically supports the types listed in the Java ™ programming language. The simplest form of enumeration is similar to the C, C ++, and C # formats.

Sample code

package com.example.enums;

/**Define a simple enum*/
public enum MetaName {
  FOO, BAR, BAZ;
}
package com.example.enums;

/**Define an enum with one value*/
public enum OneValueEnum {

  ONE(1), TWO(2), THREE(3);

  private final int number;

  /**
   *Generate an enum constant by specifying a value.
   */
  OneValueEnum(int number) {
    this.number = number;
  }

  /**
   *Prepare a method that returns a value.
   */
  public int getNumber() {
    return number;
  }

  /**
   *Returns an enum constant that matches the value.
   */
  public static OneValueEnum getByNumber(int number) {
    //Processing that identifies and returns an enum constant from a value
    for (OneValueEnum value : OneValueEnum.values()) {
      if (value.getNumber() == number) {
        return value;
      }
    }
    return null; //If not identifiable
  }
}
package com.example;

import com.example.enums.MetaName;
import com.example.enums.OneValueEnum;

public class Main {

  public static void main(String[] args) {
    testMetaName();
    testOneValueEnum();
  }

  private static void testMetaName() {
    try {
      //You can get an Enum constant from a string using the auto-generated valueOf method
      System.out.println("***** FOO *****");
      MetaName foo = MetaName.valueOf("FOO");
      System.out.println("foo.getClass=" + foo.getClass());
      System.out.println("foo.getDeclaringClass=" + foo.getDeclaringClass());
      System.out.println("foo.toString=" + foo.toString());

      //IllegalArgumentException occurs when trying to get a constant that does not exist
      System.out.println("***** bar *****");
      MetaName bar = MetaName.valueOf("bar");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private static void testOneValueEnum() {
    try {
      //You can get an Enum constant from a string using the auto-generated valueOf method
      System.out.println("***** ONE *****");
      OneValueEnum one = OneValueEnum.valueOf("ONE");
      System.out.println("one.getClass=" + one.getClass());
      System.out.println("one.getDeclaringClass=" + one.getDeclaringClass());
      System.out.println("one.toString=" + one.toString());
      System.out.println("one.getNumber=" + one.getNumber());

      //In order to get the Enum constant that matches the value, you need to implement it yourself.
      System.out.println("***** 1 *****");
      OneValueEnum ichi = OneValueEnum.getByNumber(1); //Call your own implementation method
      System.out.println("ichi.getClass=" + ichi.getClass());
      System.out.println("ichi.getDeclaringClass=" + ichi.getDeclaringClass());
      System.out.println("ichi.toString=" + ichi.toString());
      System.out.println("ichi.getNumber=" + ichi.getNumber());

      //Since there was no Enum constant that matches the value, null is returned.
      // (Since it is self-implemented, you can do any processing)
      System.out.println("***** 9 *****");
      OneValueEnum kyu = OneValueEnum.getByNumber(9);
      System.out.println("kyu=" + kyu);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Build sample code

Place the source code.

$ tree
.
└── src
    └── com
        └── example
            ├── Main.java
            └── enums
                ├── MetaName.java
                └── OneValueEnum.java

Create a directory to output the class file.

$ mkdir dest

Compile with the javac command.

$ javac -sourcepath src src/com/example/Main.java -d dest

Confirm that the class file has been generated.

$ tree
.
├── dest
│   └── com
│       └── example
│           ├── Main.class
│           └── enums
│               ├── MetaName.class
│               └── OneValueEnum.class
└── src
    └── com
        └── example
            ├── Main.java
            └── enums
                ├── MetaName.java
                └── OneValueEnum.java

Sample execution result

$ java -classpath dest com.example.Main
***** FOO *****
foo.getClass=class com.example.enums.MetaName
foo.getDeclaringClass=class com.example.enums.MetaName
foo.toString=FOO
***** bar *****
java.lang.IllegalArgumentException: No enum constant com.example.enums.MetaName.bar
	at java.lang.Enum.valueOf(Enum.java:238)
	at com.example.enums.MetaName.valueOf(MetaName.java:3)
	at com.example.Main.testMetaName(Main.java:23)
	at com.example.Main.main(Main.java:9)
***** ONE *****
one.getClass=class com.example.enums.OneValueEnum
one.getDeclaringClass=class com.example.enums.OneValueEnum
one.toString=ONE
one.getNumber=1
***** 1 *****
ichi.getClass=class com.example.enums.OneValueEnum
ichi.getDeclaringClass=class com.example.enums.OneValueEnum
ichi.toString=ONE
ichi.getNumber=1
***** 9 *****
kyu=null

Reference material

-JDK 5.0 documentation -enum

Recommended Posts

Reverse Enum constants from strings and values in Java
Get attributes and values from an XML file in Java
Reverse Key from Value in Java Map
Capture and save from selenium installation in Java
Generate OffsetDateTime from Clock and LocalDateTime in Java
Convert Java enum enums and JSON to and from Jackson
[Java] [Kotlin] Generically call valueOf and values of Enum
Reproduce Java enum in C #
JSON in Java and Jackson Part 1 Return JSON from the server
Implement Java Interface in JRuby class and call it from Java
Correct the character code in Java and read from the URL
Define abstract methods in Java enum and write each behavior
Differences in how to handle strings between Java and Perl
Management of partitioned values and their names Enum (Java) vs DB
Note No. 1 "Counting and displaying duplicate values in an array" [Java]
Java arguments, return values and overloads
[Java] Remove whitespace from character strings
StringBuffer and StringBuilder Class in Java
Write keys and values in Ruby
Understanding equals and hashCode in Java
Hello world in Java and Gradle
How to concatenate strings in java
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript
Gradle automatically generates version number from git and uses it in Java
Study Deep Learning from scratch in Java.
Java starting from beginner, variables and types
Difference between final and Immutable in Java
[Java] Compare values / strings (AOJ14 --card game)
Call Java method from JavaScript executed in Java
OCR in Java (character recognition from images)
[Java] for Each and sorted in Lambda
Using JavaScript from Java in Rhino 2021 version
Get history from Zabbix server in Java
Arrylist and linked list difference in java
Program PDF headers and footers in Java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
[Java] enum
[Deep Learning from scratch] in Java 1. For the time being, differentiation and partial differentiation
GetInstance () from a @Singleton class in Groovy from Java
Regarding the transient modifier and serialization in Java
Create barcodes and QR codes in Java PDF
Detect similar videos in Java and OpenCV rev.2
Java method call from RPG (method call in own class)
Parallel and parallel processing in various languages (Java edition)
Difference between next () and nextLine () in Java Scanner
Differences in writing Java, C # and Javascript classes
How to get Class from Element in Java
Text extraction in Java from PDF with pdfbox-2.0.8
Get unixtime (seconds) from ZonedDateTime in Scala / Java
Add, read, and delete Excel comments in Java
Check static and public behavior in Java methods
[Java] Understand in 10 minutes! Associative array and HashMap
Basics of threads and Callable in Java [Beginner]
[Java] Get multiple values from one return value
[Deep Learning from scratch] in Java 3. Neural network
Get Enum by reverse lookup from the contents