Enum String

J

Jason Cavett

Is it possible to get a String back from an enum value? Here is a
sample of my enum:

// XML tags
public enum XML {
DATA_TAG("data");

private final String tag;


private XML(String tag) {
this.tag = tag;
}

@Override
public String toString() {
return tag;
}
}

Now, I could like to be able to just call: XML.DATA_TAG and that
returns a String. Is this possible? Something is telling me that
I'll always have to call the toString() function as well, but I wanted
to check first.

Thanks
 
L

Lew

Jason said:
Is it possible to get a String back from an enum value? Here is a
sample of my enum:

// XML tags
public enum XML {
DATA_TAG("data");

private final String tag;


private XML(String tag) {
this.tag = tag;
}

@Override
public String toString() {
return tag;
}
}

Now, I could like to be able to just call: XML.DATA_TAG and that
returns a String. Is this possible? Something is telling me that
I'll always have to call the toString() function as well, but I wanted
to check first.

Given that DATA_TAG is not of type String itself, yes, you'll have to call
toString() just like for any other object if you want a String representation.
 
J

Jason Cavett

Given that DATA_TAG is not of type String itself, yes, you'll have to call
toString() just like for any other object if you want a String representation.

Alright. I sort of figured that I would. It kind of stinks, though,
because wherever I was using my static Strings before, I now have to
do:

Data::XML::DATA_TAG.toString()
instead of
Data::DATA_TAG

Seems kind of dumb to make the XML tags into an enum. Any opinion/
argument one way or another?
 
S

Stefan Ram

Jason Cavett said:
Now, I could like to be able to just call: XML.DATA_TAG and that
returns a String. Is this possible?

You can pass an object instead of the string value of that
object, if the callee will invoke »toString()« himself.

For example, the following programm prints the string value
»alpha« of the object »new Text()« even though »toString()«
is not explicitly invoked within the following source code.

class Text
{ public java.lang.String toString(){ return "alpha"; }}

public class Main
{ public static void main( final java.lang.String[] args )
{ java.lang.System.out.println( new Text() ); }}

alpha
 
M

Mark Space

Jason said:
Seems kind of dumb to make the XML tags into an enum. Any opinion/
argument one way or another?

Java has several XML parsers available in the standard API. SAX, JDOM,
XPath, plus probably a few more. Maybe look at one of those?
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top