2016-09-17 55 views
0

我无法将接口添加到groovy枚举。添加接口到groovy枚举?

例如:

接口DeviceType.groovy

public interface DeviceType{ 
    public String getDevice() 
} 

枚举Device.groovy

public enum Devices implements DeviceType { 

    PHONE{ 
     public String getDevice(){ 
      return "PHONE" 
     } 
    }, ALARM { 
     public String getDevice(){ 
      return "ALARM" 
     } 
    } 
} 

简单测试

public class MainTest(){ 

    public static void main(String [] args) { 
    System.out.println(Devices.PHONE.getDevice()); 
    //should print phone 
    } 
} 

这是伪代码,而是一个相当不错的例。 当我将它与Groovy一起使用时,我从IntelliJ中得到一个错误,我需要使该接口变为抽象。 如果我把它抽象化,maven不会编译它说它不能既是静态的也是最终的。

任何提示?

+0

注意:Devices.PHONE.getDevice(); – Will

+0

这肯定会在mvn测试中破解。 – Will

+0

错误:(23,1)Groovyc:在非抽象类中不能有抽象方法。类'xxx'必须声明为抽象或者必须实现方法'getDevice()'。 – Will

回答

2

您需要在enum中定义getDevice()。由于枚举是一个类,你的类实现接口,它需要实现的功能

枚举Device.groovy

public enum Devices implements DeviceType { 

    PHONE{ 
     public String getDevice(){ 
      return "PHONE" 
     } 
    }, ALARM { 
     public String getDevice(){ 
      return "ALARM" 
     } 
    }; 

    public String getDevice(){ 
     throw new UnsupportedOperationException(); 
    } 

} 
1

:然后你就可以覆盖它,像这样。现在你所拥有的是一个不实现该函数的枚举,其实例是每个具有相同名称的函数的子类。但由于枚举本身没有它,这还不够好。

我想提供我的首选语法的情况下,如本:

public enum Devices implements DeviceType { 
    PHONE("PHONE"), ALARM("ALARM") 
    private final String devName 
    public String getDevice() { return devName } 
    private Devices(devName) { this.devName = devName } 
} 

或者,如果“设备”总是会匹配枚举实例的名称,你还不如只需返回:

public enum Devices implements DeviceType { 
    PHONE, ALARM 
    public String getDevice() { return name() } 
}