Re: an enum question - how to convert enum type to a string?

Discussion in 'Java' started by Lew, Feb 27, 2010.

  1. Lew

    Lew Guest

    www wrote:
    > Hi,
    >
    > I am new to enum. Suppose I have the following enum
    >
    > packcage A.B.C


    This line will not compile, due to the misspelling and lack of semicolon.

    Conventionally, packages are named with all lower-case letters.

    > enum CarModel
    > {
    > BMW, HONDA, FORD
    > }
    >
    > In my program, I need to get the string "CarModel" from enum CarModel.
    > Is there a way to do it?


    Of course.

    > Note: I am not talking about getting string "BMW", "HONDA" etc. I know
    > CarModel.BMW.toString() will give me "BMW".
    >
    > I also prefer to get "CarModel" string, not "A.B.C.CarModel".


    It's rather bizarre to use a class name; I've seen it done in production code
    many times where it causes fragility, inefficiency and bugs. Part of the
    problem is that use of the class name violates a kind of programming Gödelian
    incompleteness. It breaks type safety when used carelessly, as I've often
    seen it used, by passing class relationships around through strings rather
    than types. Some uses I've seen require particular naming relationships
    between types for them to work together, though actual object-oriented
    programming would have worked more easily and more flexibly.

    Regardless, you do it the usual way, with
    <http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getSimpleName()>

    --
    Lew
    Lew, Feb 27, 2010
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. guoqi zheng

    convert type string to type guid

    guoqi zheng, Jul 2, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    13,369
    =?Utf-8?B?QmlsbCBCb3Jn?=
    Jul 2, 2005
  2. Replies:
    6
    Views:
    952
    Greg Comeau
    Oct 20, 2005
  3. Eric Sosman
    Replies:
    3
    Views:
    778
    Mayeul
    Feb 26, 2010
  4. Wojtek
    Replies:
    1
    Views:
    495
  5. Roedy Green
    Replies:
    0
    Views:
    728
    Roedy Green
    Feb 27, 2010
Loading...

Share This Page