Sonhja
Sonhja

Reputation: 8448

Get type of specific enum

I have a class that contains several enumerateds, like this:

public class MyEnumerateClass
{
    public enum Enum1
    {
        enum1Value1,
        enum1Value2
    }

    public enum Enum2
    {
        enum2Value1,
        enum2Value2
    }
 }

I have a method that takes any of that Enums like this:

 public void GetValue(MyEnumerateClass enumerateField)
 {
      switch (enumerateField)
      {
          case enum1Value1:
             ... do stuff here ...
             break;
      .......... stuff ..........
      }
  }

As we can appreciate, that GetValue allows me to accept any of the two values declared previously. But I have a problem:

When I need to check the enumerate type and check if it's Enum1 or Enum2, I don't know how to handle it...

 public void GetType(MyEnumerateClass enumerateField)
 {
        enumerateField.values(); // To do this I need to know the type of the enumerate
 }

So, how can I get the enumerate type if it's inside MyEnumerateClass?

Upvotes: 0

Views: 3976

Answers (3)

Bohemian
Bohemian

Reputation: 425003

Every enum extends Enum<?>, so you can limit the parameter to being an enum instance using this type. Then use instanceof inside the method:

public void GetValue(Enum<?> enumerateField) {
    if (enumerateField instanceof Enum1) {
        switch (enumerateField) {
            case enum1Value1:
              // ... do stuff here ...
            break;
             // .......... stuff ..........
        }
    } else (enumerateField instanceof Enum2) {
        // whatever
    }   
}

Upvotes: 1

squiddle
squiddle

Reputation: 1317

Every enum is its own type (in your example they behave like static inner classes in that regard).

To have one method parameter allowing both enums either you have to build a type hierarchy or take Object as the param value. As you know which possible types you can receive (MyEnumerateClass $Enum1 or MyEnumerateClass$Enum2) you can use an instanceof check and branch on the type of your parameter or you overload the method for both enums.

void GetValue(Object o){
    if(o instanceof MyEnumerateClass.Enum1) {
        switch((MyEnumerateClass.Enum1) o){
        case enum1value1: ...
        }
    } else if (o instanceof MyEnumerateClass.Enum2) {
        switch((MyEnumerateClass.Enum2) o){
        case enum2value1: ...
        }
    }
}

or

class A {
    void GetValue(MyEnumerateClass.Enum1 value){}
    void GetValue(MyEnumerateClass.Enum2 value){}
}

Upvotes: 3

Radhamani Muthusamy
Radhamani Muthusamy

Reputation: 328

Enum is like Class,Interface so the creation of enum could not be within the class as per my understanding.

public enum Enum1
    {
        enum1Value1,
        enum1Value2
    }
    public enum Enum2
    {
        enum2Value1,
        enum2Value2
    }
Then you can create a object and use enum value. You can refer What's the use of "enum" in Java? for more details.

Upvotes: 1

Related Questions