Darth.Vader
Darth.Vader

Reputation: 6271

Passing enum types as parameters in java

I have two types of enums:

public static enum Type1 {
  T1_A,
  T1_B
}

and

public static enum Type2 {
  T2_A,
  T3_B
}

I want to be able to write an API which can take either of these enums (Type1 or Type2) as parameters and do something with them. How can I design a method which let's me choose the Type of the enum during runtime?

Something to the effect of:

    void fun(?? type1_or_type2) {
         // something goes here...
    }

Upvotes: 2

Views: 2324

Answers (5)

Gingerade
Gingerade

Reputation: 134

You could pass the Enum class as the parameter.

void fun(Class<? extends Enum<?>> yourEnum) {
    // Do something here. Here's how you would get an array of the Enum values.
    yourEnum.getEnumConstants();
}

You would pass Type1 in.

fun(Type1.class);

Upvotes: 1

Buhake Sindi
Buhake Sindi

Reputation: 89169

Alternatively, this might be an approach to look at:

public interface SomeInterface {
    public void interface(Type1 type);
    public void interface(Type2 type);
}

Upvotes: 3

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try this:

    interface Marker {

    }

    enum Type1 implements Marker {
        T1_A, T1_B
    }

    enum Type2 implements Marker {
        T2_A, T3_B
    }


    void fun(Marker e) {
    // something goes here...
    if (e instanceof Type1) {
        // Do Type1 specific
    } else if (e instanceof Type2) {
        // Do Type2 specific
    }

   }

Upvotes: 1

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32468

Define an interface, and implement that interface in you enum classes. Then use the Interface type as the parameter

interface Type {
    ...
}

public static enum Type1 implements Type {
  T1_A,
  T1_B
}

public static enum Type2 implements Type {
  T2_A,
  T2_B
}

void fun(Type aType) {
         // something goes here...
    }

Upvotes: 3

Toon Borgers
Toon Borgers

Reputation: 3658

You can create a marker interface with no methods in it and let the enums implement that interface. Next, use the interface as the parameter type on your method.

Upvotes: 7

Related Questions