简体   繁体   English

如何在Groovy类中调用接口的默认方法

[英]How to call default method of interface in groovy Class

I have groovy class Page which implements a interface named IImageOperations. 我有一个时髦的类Page,它实现了一个名为IImageOperations的接口。

This interface contain a default method addImage. 此接口包含默认方法addImage。 Which i wanted to call from Page class. 我想从Page类调用它。

I tried to call in below manner 我尝试以以下方式致电

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

But, it is giving me below error 但是,这给了我下面的错误

Groovy:The usage of 'Class.this' and 'Class.super' is only allowed in nested/inner classes. Groovy:仅在嵌套/内部类中允许使用“ Class.this”和“ Class.super”。

If we define this Page class as Java Class, then things are working fine. 如果我们将此Page类定义为Java类,那么一切正常。

the following correct java code 以下正确的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() );
    }

}

failed to compile under 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() );

however the following syntax works fine (groovy 2.4.11): 但是以下语法可以正常工作(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() );
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM