Java Data Type How to - Convert String to enum value when enum type reference is a Class








Question

We would like to know how to convert String to enum value when enum type reference is a Class.

Answer

import java.lang.annotation.*;
/*from   w  w  w.jav a2 s. c o m*/
public class Main {
    public static void main(String[] args) {
        Class enumType = RetentionPolicy.class;
        String name = "SOURCE";

        Enum e = Enum.valueOf(enumType, name);
        System.out.println(e);
    }
}

prints

SOURCE

The code above generates the following result.