无法在Groovy中扩展通用接口

时间:2019-11-19 22:25:47

标签: oop generics inheritance grails groovy

我正在尝试在groovy中实现一个称为ObjectPostProcessor接口的spring接口,以创建一个新类。 我尝试使用实现该接口的新类并通过创建一个新的匿名类来做到这一点。我一直看到错误信息。

Groovyc:非抽象类中不能有抽象方法。

这让我认为groovy并不认为该类的抽象方法被正确覆盖了。

下面是要中断的代码示例。

在Groovy中实现这种接口的正确方法是什么?

interface ObjectPostProcessor<T> {

    /**
     * Initialize the object possibly returning a modified instance that should be used
     * instead.
     *
     * @param object the object to initialize
     * @return the initialized version of the object
     */
    public <O extends T> O postProcess(O object);
}

// groovy error Error:(15, 1) Groovyc: Can't have an abstract method in a non-abstract class. The class 'ObjectPostProcessorImpl' must be declared abstract or the method 'java.lang.Object postProcess(java.lang.Object)' must be implemented.
class ObjectPostProcessorImpl implements ObjectPostProcessor<Integer> {

    @Override
    public <O extends Integer> O postProcess(O object) {
        return object
    }
}

class Anon {
    public static void main(String[] args) {

        ObjectPostProcessor<Integer> objectPostProcessor  = new ObjectPostProcessor<Integer>() {

            /** Groovyc: Can't have an abstract method in a 
             * non-abstract class. 
             * The class 'ObjectPostProcessorImpl' must 
             * be declared abstract or the method 
             * 'java.lang.Object postProcess(java.lang.Object)' 
             * must be implemented. */

            @Override
            public <O extends Integer> O postProcess(O object) {
                return object;
            }
        };

        ObjectPostProcessorImpl objectPostProcessorImplObj = new ObjectPostProcessorImpl();

        System.out.println(objectPostProcessor.postProcess(12));
        System.out.println(objectPostProcessorImplObj.postProcess(12));
    }
}

0 个答案:

没有答案