groovy - 覆盖抽象枚举方法

标签 groovy enums

以下是有效的 Java 代码:

enum ProductType {
  CASH_BONUS { 

     void doSomething() {}    
  },

  CUSTOMIZABLE { 
     void doSomething() {}    
  }

  abstract void doSomething()
}

但是当我尝试在 Groovy 控制台中运行它时,出现错误:

Can't have an abstract method in a non-abstract class. The class 'ProductType' must be declared abstract or the method 'void doSomething()' must be implemented. at line: -1, column: -1

Can't have an abstract method in a non-abstract class. The class 'ProductType' must be declared abstract or the method 'void doSomething()' must not be abstract. at line: 11, column: 3



我似乎记得读过 Groovy 不(还)支持枚举常量的覆盖方法,这是正确的,如果是,是否有一种优雅的方式来模拟这种行为?

更新

这是一个在 Groovy 1.8.0 前后修复的错误

最佳答案

这是一个错误:http://jira.codehaus.org/browse/GROOVY-4641

您可以使抽象方法不抽象。抛出一个异常以确保你总是像这样覆盖它:

enum ProductType {
    CASH_BONUS(1) {
        void doSomething() {
        }
    },
    CUSTOMIZABLE(2) {
        void doSomething() {
        }
    };
    ProductType(int n) {
        this.n=n;
    }
    final int n;
    void doSomething() {
        throw new UnsupportedOperationException()
    }
}

ProductType.CASH_BONUS.doSomething();
ProductType.CUSTOMIZABLE.doSomething();

关于groovy - 覆盖抽象枚举方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099152/

相关文章:

java - 处理多部分/表单数据请求时,Spring Boot 1.3.7 中的文件始终为空

java - 了解 Groovy/Grails 类加载器泄漏

ios - Swift 枚举作为函数中的参数

java - Groovy Classpath 上的 Jenkins 包?

ubuntu - 返回java中的事件窗口标题

java - 将 EnumType 传递给 Postgres 函数

c - 枚举错误,变量未声明

ios - NSDictionary,如何存储和读取枚举值?

Java 枚举定义

grails - 使用 boolean 值捕获用户列表,spring security