0

I have a simple enum

public enum Columns {VENDOR, ITEM};

That I am trying to extract and drive a switch code block.
What I am getting classNotFound for what appears to be the inner class for the enum, b/c it shows [class]_A$0. I thought enum was a static final and created object that I could use directly in the switch. Can someone clarify?

      colObject="VENDOR";
      for (Columns c : Columns.values()) {
        if (colObject.toUpperCase().equals(c.name())) {
          System.out.println("Got it in iteration. i= " + i + " c= " +
                             c);
          switch (c.valueOf(colObject.toUpperCase())) {
            case VENDOR: {
              System.out.println("Got it in switch case= " + c.name());
            }
            break;
            default:
              System.out.println("Fell thru.");
              break;
          }//end switch
        }//end if
      }//end for
2
  • 1
    Works for me (output is "Got it in switch case= VENDOR") - no compile time or runtime errors. Can you provide a complete SSCCE which reproduces the issue, and some additional information on the JDK version you are using? Commented Apr 3, 2013 at 11:39
  • 1
    Yes, your code as shown works (though you do need to fix that static access from a non-static context). Include the full stack trace and an SSCCE as suggested by Andreas. Commented Apr 3, 2013 at 11:42

2 Answers 2

4

Try:

switch (Columns.valueOf(colObject.toUpperCase())) {
Sign up to request clarification or add additional context in comments.

1 Comment

While it is true that calling a static method (valueOf()) on an object rather than on the class is bad practice, it technically does not make a difference. Both variants worked for me.
2

you can use java.lang.Enum class. Enum class will help to convert your String "VENDOR" to enum-VENDOR

Need to add following line of code

Enum.valueOf(Columns.class, colObject))

java.lang.Enum can be used polymorphically whereas Columns(enum) cannot be used polymorphically.

Complete code

enum Columns {
    VENDOR, ITEM
}

class Test {
    public static void main(String[] args) {
        String colObject = "VENDOR";

        switch (Enum.valueOf(Columns.class, colObject)) 
        {
            case VENDOR: {
                System.out.println("Got it in switch case= VENDOR");
                break;
            }
            default:
                System.out.println("Fell thru.");
                break;
            }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.