How to create an interface for such an enumeration

I have the following listing:

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 a StringEnum interface to make sure all enums have find (), toString () and a constructor?

Thanks.

+4
source share
3 answers

Cannot specify constructors or static methods in an interface. For a good and concise explanation, check out this article: No static methods in interfaces

+6
source

Enumerations already have a valueOf () method (your search method). And "toString ()" is the java.lang.Object method, so every class will have this, in other words, you cannot force it! I do not see the meaning of forced constructor use, since different enums can have different initializations.

Yours faithfully

+4
source
  • static methods cannot be defined in interfaces
  • constructors cannot be defined in interfaces
  • toString defined in java.lang.Object , requiring that it never cause a compilation error in the interface if the method is not defined.

Why do you still want to force the use of the constructor? You cannot create new instances of enum at run time in any way (unless, perhaps, through some kind of reflection mechanism).

+3
source

Source: https://habr.com/ru/post/1276997/


All Articles