Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Enums implementing the same interface sharing a method

Tags:

java

enums

I have two Enums implementing the same interface

public interface MetaEnum{
    String getDefaultValue();
    String getKey();
}

public enum A implements MetaEnum{
   ONE("1"), TWO("2");
   private String val;
   A(final v){
       val = v;
   }
   @Override
   public String getDefaultValue() {
       return value;
   }
   @Override
   public String getKey() {
        return (this.getClass().getPackage().getName() + "." + this.getClass().getSimpleName() + "." +
            this.toString()).toLowerCase();
   }
}

public enum B implements MetaEnum{
   UN("1"), DEUX("2");
   private String val;
   B(final v){
       val = v;
   }
   @Override
   public String getDefaultValue() {
       return value;
   }
   @Override
   public String getKey() {
        return (this.getClass().getPackage().getName() + "." + this.getClass().getSimpleName() + "." +
            this.toString()).toLowerCase();
   }
   ...other methods specific to this enum
}      

I have duplicated code and I would like to avoid it. Is there a way to implement getKey in a sort of abstract class? I looked at this question Java Enum as generic type in Enum but it cannot adapt it to what I need.

like image 442
Paul Fournel Avatar asked Feb 27 '26 16:02

Paul Fournel


1 Answers

The default method from Java 8 should help you :)
This feature allows you to implement method inside an interface.

public interface MetaEnum {
  String getValue();  

  default String getKey() {
    return (this.getClass().getPackage().getName() + "." + 
            this.getClass().getSimpleName() + "." +
            this.toString()).toLowerCase();
  }
}

Unfortunately, you can't implement a default method for getters, so you still have some duplicate code.

like image 145
NiziL Avatar answered Mar 01 '26 12:03

NiziL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!