gpt4 book ai didi

java - 如何调用groovy类中接口(interface)的默认方法

转载 作者:行者123 更新时间:2023-12-02 10:40:51 25 4
gpt4 key购买 nike

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

该接口(interface)包含一个默认方法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 类,那么一切工作正常。

最佳答案

以下正确的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() );
}

}

关于java - 如何调用groovy类中接口(interface)的默认方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52927063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com