【问题标题】:How to call default method of interface in groovy Class如何在groovy类中调用接口的默认方法
【发布时间】:2018-10-22 10:21:48
【问题描述】:

我有一个 groovy 类 Page,它实现了一个名为 IImageOperations 的接口。

这个接口包含一个默认方法addImage。我想从 Page 类中调用它。

我试着用下面的方式打电话

class Page implements IImageOperations, ITextOperations {

void addImage(PDImageXObject image, float x, float y, float w = 0, float h = 0, float rotate = 0, boolean inline){
    if(w == 0)
        w = image.getWidth();
    if(h == 0)
        h = image.getHeight();
    IImageOperations.super.addImage("", 0, 0);
}
}

但是,它给了我以下错误

Groovy:“Class.this”和“Class.super”的使用只允许在嵌套/内部类中使用。

如果我们将这个 Page 类定义为 Java 类,那么一切正常。

【问题讨论】:

  • 你试过简单的addImage("", 0, 0)吗?
  • 请提供您如何声明您的班级。
  • @SzymonStepniak,是的,我试过了,仍然 eclipse 显示错误
  • @daggett -- 添加了完整的 groovy 类
  • @daggett -- 感谢您的帮助。好像我们可以直接使用它,不用super。 Eclipse 显示错误错误。

标签: java groovy


【解决方案1】:

以下正确的java代码

import java.lang.reflect.Type;


public class A implements Type{
    public static void main(String [] arg){
        new A().run();
    }

    public void run(){
        System.out.println( Type.super.getTypeName() );
    }

}

在groovy下编译失败:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
A.groovy: 10: The usage of 'Class.this' and 'Class.super' is only allowed in nested/inner classes.
 @ line 10, column 23.
                System.out.println( Type.super.getTypeName() );

但是以下语法可以正常工作(groovy 2.4.11):

import java.lang.reflect.Type;

public class A implements Type{
    public static void main(String [] arg){
        new A().run();
    }

    public void run(){
        //System.out.println( Type.super.getTypeName() );
        System.out.println( ((Type)this).getTypeName() );
    }

}

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 2018-09-14
    • 2017-09-28
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多