The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
July 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Re: typesafe java enum

Posted by Michael Ovington on July 31, 2001 at 12:03 PM

> I have a class that employs the typesafe java enum pattern described in eckel's book "thinking in java" p. 276.

> Here is the code:

> public final class AvailabilityStatus {
> private final String name;

> private AvailabilityStatus(String name) {
> this.name = name;
> }

> public String toString() {
> return name;
> }

> public static final AvailabilityStatus
> IN_STOCK = new AvailabilityStatus("IN_STOCK"),
> BACKORDER = new AvailabilityStatus("BACKORDER"),
> DISCONTINUED = new AvailabilityStatus("DISCONTINUED"),
> NOT_AVAILABLE = new AvailabilityStatus("NOT_AVAILABLE");

> }

>
> The problem I am having is that I read an XML attribute string and then I want to set the enum. There is no ELEGANT means to set the enum class above with a string. I would be forced to do a string compare to each string and then return the appropriate availability status.

> Does anyone know how to do this is a clean way without all the string comparisons?

No.

You have to do the string compares somewhere, just as you
would in a language like C that has enums. There generally is
no runtime information about the string that the enum value
started as.

Extend the enum pattern with

public static AvailabilityStatus
fromString( String s)

and have your constructor put all new instances in a static
ArrayList. That way the implementation of fromString is
essentially the same for all your enums.



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us