Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a method parameter as any enum

I have a method on which I need to pass an enum as a parameter.

public <T> T doSomething(SomeEnum operation, Class<T> something); 

I have several enums and the method is a common one which should work with any enums. What is the correct way to write this method signature to accept any generic enum types? I know that I can use a marker interface to this purpose, but I would like to write it with generic enum signatures. Please advise me on this.

Whats the bad idea with the below one: (It works but I get warnings from IDE saying it is a raw type. I'm not clear about the reason).

 public void doSomething(Enum operation); 
like image 414
popcoder Avatar asked Jul 11 '12 14:07

popcoder


People also ask

Can you declare enum in method?

You cannot define enums within methods, but you can define classes, so if you really wish to design your method in this way, you can define an array of your local class object.

How do you pass an enum in a method argument?

Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum. Show activity on this post. Show activity on this post. First change the method parameter Enum supportedPermissions to SupportedPermissions supportedPermissions .

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.


1 Answers

public <E extends Enum<E>> void doSomething(E operation); 

EDIT: An example according to your modifications:

public class Main {      public enum Day {         SUNDAY, MONDAY, TUESDAY, WEDNESDAY,         THURSDAY, FRIDAY, SATURDAY      }      public <E extends Enum<E>> E doSomething(E operation, Class<E> klazz) {          return operation;     }      public static void main(String[] args) {          new Main().doSomething(Day.FRIDAY, Day.class);     }  } 

EDIT2:

if you need T and the Enum as separate types, then you'll need:

public <T, E extends Enum<E>> T doSomething(E operation, Class<T> klazz) { 
like image 132
Istvan Devai Avatar answered Sep 18 '22 08:09

Istvan Devai