views:

972

answers:

3

I have the following enum:

public enum Status implements StringEnum{ 

 ONLINE("on"),OFFLINE("off");

 private String status = null;

 private Status(String status) {
  this.status = status;
 }

 public String toString() {
  return this.status;
 }

 public static Status find(String value) {
  for(Status status : Status.values()) {
   if(status.toString().equals(value)) {
    return status;
   }
  }

  throw new IllegalArgumentException("Unknown value: " + value );

 }
}

Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?

Thanks.

+4  A: 

It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: No static methods in interfaces

Frank Pape
+3  A: 
  1. static methods cannot be defined in interfaces
  2. constructors cannot be defined in interfaces
  3. toString is defined in java.lang.Object, requiring it in an interface will never result in a compile error if the method isn't defined.

Why do you want to enforce the constructor anyway? You cannot create new instances of enums at runtime anyway (unless maybe via some reflection mechanism).

Torsten Marek
+2  A: 

Enums already have a valueOf (your find method) method. "toString" is a java.lang.Object, so, every class will have that, in other words, you can't force it! I can't see the value of enforcing a constructor since different enums could have different initializations.

Kind Regards

marcospereira