enum: display elements of an enum specified at runtime

J

Jerminia

Hello,

I have the following problem:

I need to perform validation on an input parameter that is a String.
This String has to be one of the values of an enumeration.
The problem is that the enumeration type is not known until runtime - thus
the caller tells me that the concerned enum by specifying its full
qualified name.

e.g.
boolean validateStringOnEnum( String toTest, String
enumFullQualName);

Does anybody know what the code would look like?

Cheers!
 
T

Tor Iver Wilhelmsen

Jerminia said:
boolean validateStringOnEnum( String toTest, String
enumFullQualName);

Use Class.forName() to get the enum class, then call the static method
"valueOf" via reflection. toTest would then be passed as the second
argument.
 
R

Roedy Green

I need to perform validation on an input parameter that is a String.
This String has to be one of the values of an enumeration.
The problem is that the enumeration type is not known until runtime - thus
the caller tells me that the concerned enum by specifying its full
qualified name.

e.g.
boolean validateStringOnEnum( String toTest, String
enumFullQualName);

Does anybody know what the code would look like?

An enum has to be known at compile time. What perhaps you want is a
HashMap that converts the legal external strings into some short form
to put in your database.

Try JComboBox for interacting with the user.

See http://mindprod.com/jgloss/jcombobox.html
http://mindprod.com/jgloss/hashmap.html
 
R

Roedy Green

the enumeration type is not known until runtime

There are two ways of interpreting that.

1. the enums are all standard enums and the code for them is known an
compile time, but which particular enum applies to a piece of data is
not known until run time.

2. the enums and their constants are not known at compile time. I
have to somehow construct enums on the fly at run time and use them.

Thomas assumed the first interpretation and I the second.

There is another low-tech way of handling the first interpretation.

if ( enumtype.equals("fruit") )
return Fruit.valueOf ( candidate );
else if ( enumtype.equals("vegetable") )
return Vegetable.valueOf ( candidate );

If the number of enums becomes unwieldy, create a HashMap of Delegate
objects indexed by enum name, that each implement
an interface with a valueOf method.

see http://mindprod.com/jgloss/delegate.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top