加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

groovy – 覆盖抽象枚举方法

发布时间:2020-12-14 16:28:13 所属栏目:大数据 来源:网络整理
导读:以下是有效的 Java代码: enum ProductType { CASH_BONUS { void doSomething() {} },CUSTOMIZABLE { void doSomething() {} } abstract void doSomething()} 但是当我尝试在Groovy控制台中运行它时,我得到错误: Can’t have an abstract method in a non-a
以下是有效的 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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读