首页 > 解决方案 > 在私有方法上使用闭包子类化一个类

问题描述

我有一个 Groovy 类,它恰好有调用私有方法的闭包。它工作得很好,直到我尝试创建它的子类,导致MissingMethodException.

示例代码:

class SomeClass {
    void doStuff() {
        println(['a', 'b'].collect { toUpper(it) })
    }

    private String toUpper(String x) {
        return x.toUpperCase()
    }
}

class Wat {
    static void main(String[] args) {
        def x = new SomeClass() {}
        x.doStuff()
    }
}

...崩溃:

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static com.example.Wat.toUpper() is applicable for argument types: (String) values: [a]
    at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1573)
    at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1559)
    ...

难道我做错了什么?除了保护所有方法之外,是否有一个明智的出路?

标签: groovy

解决方案


我无法提供更好的解决方案,只能使用中间函数:


class SomeClass {
    void doStuff() {
        println(['a', 'b'].collect { pass(it) })
    }

    def pass(x) { toUpper(x) }

    private String toUpper(String x) {
        x.toUpperCase()
    }
}


def x = new SomeClass() {}
x.doStuff()

推荐阅读