Enum objects automatically instantiated
You said:
create dynamically instance
Instances of an enum are made only once: when the class is loaded. Each constant name on that element is automatically assigned an instance of the enum`s class. Without resorting to some reflection/introspection sorcery, you cannot otherwise instantiate enum objects.
Enum::toString
The toString
method generates a String
object holding the text of the constant name.
Enum.valueOf
To go the other direction, starting with a constant name, and wanting to get an enum object, call valueOf
.
Example
enum FanSpeed {
LOW,
MEDIUM,
HIGH
}
Access one of the already-instantiate objects:
FanSpeed initialSpeed = FanSpeed.LOW ;
Or achieve the same effect by name:
FanSpeed initialSpeed =
Enum.valueOf(
FanSpeed.class ,
"LOW"
)
;
Or use the shorter version via the enum class itself: FanSpeed.valueOf( "LOW" )
.
This string-based approach is generally not necessary. By definition, all of the enum’s objects are known at compile-time. So you should be passing around the enum objects, not their names.
Be aware that the two approaches shown above both access an object that has already been instantiated when your enum class loaded. Neither approach does any instantiation, except indirectly by causing the enum’s class to load.
Class name by Reflection
If your goal is to get the class of the enum by name, use reflection.
The class named Class
represents a particular class. To obtain a Class
object for a particular class, call Class.forName
while passing the name of the desired class as a string.
Class.forName( "com.basil.FanSpeed" )
Verify that the class is indeed an enum by calling Class::isEnum
.
From that Class
object, you can get an array of all the enum’s objects by calling getEnumObjects
.
Obtain a specific enum object via this Class
object by passing the constant name to Enum.valueOf
as seen above.
Enum.valueOf(
Class.forName( "com.basil.FanSpeed" ) ,
"LOW"
)
Caveat: Use reflection only as a last resort. Often, use of reflection is a “code smell”, indicative of a design strategy needing revision.