Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface a static method for Enum

Enum.valueOf() cannot be hidden by another static method valueOf of a concrete Enum type, but since I am creating my objects with reflection from text files I need a generic way to invoke valueOf.

Currently my Enum has a static class fromString():

public enum Fruits {

   APPLE, ORANGE, ...;

    public static Fruit fromString(String fruit) {
        ...
    }
}

But how could I interface such a method that when I am dealing with an enum field type I invoke the appropriate method? The only thing I can think of is:

  • using a marker interface
  • implement this static method for every enum
  • invoke the static method via reflection

Is there another alternative which enforces this restriction?

like image 372
Mahoni Avatar asked Aug 20 '12 10:08

Mahoni


People also ask

Can an enum have static methods?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Can I put enum in interface?

Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version.

Can enum be static in C?

static enum direction {UP,DOWN,RIGHT,LEFT}; This declares an enumerated type with the tag name directions , and also defines a number of enumeration constants and their values. The static storage-class is meaningless here, because you are not defining (allocating storage) for an object.


1 Answers

If I understand correctly, you'll have a number of distinct enums that you want to integrate through the unique fromString method. What I have done is to make a separate class that accumulates all enum members into a single static final Map and the fromString method is implemented in terms of it.

All enums implement a common interface in my case because I have a number of custom methods that I need to call irrespective of the exact enum in question.

like image 95
Marko Topolnik Avatar answered Oct 02 '22 19:10

Marko Topolnik