Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Enum Instance from Class<? extends Enum> using String value?

I'm finding it difficult to put the exact question into words, so I'll just give an example.

I have two Enum types:

enum Shape {     CAT, DOG; }  enum Color {     BLUE, RED; } 

I have a method:

public Object getInstance(String value, Class<?> type); 

I would like to use the method like:

// someValue is probably "RED", and someEnumClass is probably Color.class Color c = getInstance(someValue, someEnumClass); 

I've been having trouble determining exactly how to implement getInstance(). Once you know the exact Enum class that you want to instantiate, it's easy:

Color.valueOf("RED"); 

But how can this above line be accomplished with an unknown Class? (It is, however, known that the someEnumClass is a subclass of Enum.)

Thanks!

like image 613
Craig Otis Avatar asked Jul 20 '11 21:07

Craig Otis


People also ask

Can enum extend enum?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can an enum have a string value?

Since C# doesn't support enum with string value, in this blog post, we'll look at alternatives and examples that you can use in code to make your life easier. The most popular string enum alternatives are: Use a public static readonly string. Custom Enumeration Class.

Can enum inherit from another enum Java?

You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.

How do I convert string to enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.


1 Answers

 public static <T extends Enum<T>> T getInstance(final String value, final Class<T> enumClass) {      return Enum.valueOf(enumClass, value);  } 

And the method is to be used as:

final Shape shape = getInstance("CAT", Shape.class); 

Then again, you can always use

final Shape shape = Shape.valueOf("CAT"); 

which is a shortcut for

Enum.valueOf(Shape.class, "CAT"); 
like image 175
chahuistle Avatar answered Sep 21 '22 07:09

chahuistle