lundi 25 avril 2022

Implementing Pseudo Enum Inheritance in Java using a Marker Interface

I'm using a Marker Interface to implement pseudo enum inheritance.

Let's say I define Marker class as follows:

public interface FieldInterface

Now I have have 5 enum classes that implement this interface.

enum Field1 implements FieldInterface
enum Field2 implements FieldInterface
enum Field3 implements FieldInterface
enum Field4 implements FieldInterface
enum Field5 implements FieldInterface

Each of the 5 enum "Field" class above defines a list of enums related to that field type. For example, enum Field1 might define enums: Field1A, Field1B, Field1C. Enum Field2 might define enums: Field2A, Field2B, Field2C

Now I need to convert plain text representation of each enum to the corresponding enum (similar to calling enum.valueOf(String)) without knowing which of the 5 enum classes the String belongs to.

One way to achieve this might be through reflection by first retrieving a list of all classes that implement said interface and iterating through all of the 5 enum classes until a match is found. However, I prefer to avoid reflection if possible (mainly due to performance reasons).

What other options are there to solve this problem?

Thanks





Aucun commentaire:

Enregistrer un commentaire