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

执行groovy脚本时出错

发布时间:2020-12-14 16:28:32 所属栏目:大数据 来源:网络整理
导读:代码如下: class Book{ private String title Book (String theTitle) { title=theTitle } String getTitle() { return title }}Book gina=new Book('Groovy in Action')assert gina.getTitle()=='Groovy in Action'assert getTitleBackwards(gina)=='noitc
代码如下:

class Book
{
     private String title
     Book (String theTitle)
     {
         title=theTitle
     }
     String getTitle()
     {
         return title
     }
}
Book gina=new Book('Groovy in Action')
assert gina.getTitle()=='Groovy in Action'
assert getTitleBackwards(gina)=='noitcA ni yvoorG'
String getTitleBackwards(Book)
{
    title=book.getTitle()
    return title.reverse()
}

当我用Ctrl R执行时,我得到以下编译错误.

1编译错误:

Invalid duplicate class definition of class Book : The source
Book.groovy contains at least two definitions of the class Book. One
of the classes is an explicit generated class using the class
statement,the other is a class generated from the script body based
on the file name. Solutions are to change the file name or to change
the class name. at line: 1,column: 1

有人可以解释一下这里发生了什么.

解决方法

类Book的重复类定义无效:

OP的代码清单包含两部分:

>类Book的类型定义
>一个groovy脚本,充当Book类型的客户端

Groovy将您的* .groovy文件视为脚本文件或类定义文件.脚本文件是包含不在类定义中的代码的文件.当Groovy编译脚本文件时,它隐式创建一个类来保存您的代码,并且隐式类被赋予* .groovy文件的名称.

然后编译器将尝试创建一个名为Test的类(与文件名相同)来保存println行,然后发生错误,因为现在有两个Test类定义.

比较:Blog entry with code sample for this error message

在同一文件中定义Book类和客户端脚本的方法是重命名文件,例如,到BookApp.groovy.警告:如果你这样做,Book类型只能在脚本文件中引用,即使在类路径上找到* .groovy文件,groovy也不会自动找到Book类型.

(编辑:李大同)

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

    推荐文章
      热点阅读