Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...