【问题标题】:Add interfaces to groovy enums?向 groovy 枚举添加接口?
【发布时间】:2016-09-17 03:04:36
【问题描述】:

我无法向 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 不会编译说它不能既是静态的又是最终的。

有什么建议吗?

【问题讨论】:

  • 注意:Devices.PHONE.getDevice();
  • 这肯定会在 maven 中使用 mvn test 中断。
  • 错误:(23, 1) Groovyc: 在非抽象类中不能有抽象方法。必须将类“xxx”声明为抽象类,或者必须实现方法“getDevice()”。
  • 请不要评论您自己的问题。改为编辑它以提供缺失的详细信息。

标签: maven groovy


【解决方案1】:

您需要在枚举中定义 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();
  }

}

【讨论】:

    【解决方案2】:

    由于枚举是一个类,而你的类正在实现接口,它需要实现函数。现在你所拥有的是一个没有实现函数的枚举,它的实例是每个子类都有一个同名的函数。但是由于枚举本身没有它,这还不够好。

    我想为这样的情况提供我喜欢的语法:

    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() }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 2017-07-09
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多