Groovy: Как обратиться к методу суперкласса из замыкания в методе подкласса? - PullRequest
0 голосов
/ 18 февраля 2019

Учитывая следующую настройку в test.groovy:

class Main {
  public static void main(String ... args) {
    new Child().foo()
  }

  public static class Parent {
    def foo() {
      println 'from parent'
    }
  }

  public static class Child extends Parent {
    def foo() {
      // def superRef = super.&foo  // needed to try what’s commented below
      def myClosure = {
        super.foo()  // doesn’t work, neither does anything of the following:
        // this.super.foo()
        // Child.super.foo()
        // Child.this.super.foo()
        // superRef()
        println 'from child'
      }
      myClosure()
    }
  }
}

Когда я запускаю groovy test.groovy (с Groovy 2.5.4 и, по крайней мере, со всеми другими версиями, которые я пробовал), тогда я получаю следующееошибка:

Caught: groovy.lang.MissingMethodException: No signature of method: static Main.foo() is applicable for argument types: () values: []
Possible solutions: any(), find(), use([Ljava.lang.Object;), is(java.lang.Object), any(groovy.lang.Closure), find(groovy.lang.Closure)
groovy.lang.MissingMethodException: No signature of method: static Main.foo() is applicable for argument types: () values: []
Possible solutions: any(), find(), use([Ljava.lang.Object;), is(java.lang.Object), any(groovy.lang.Closure), find(groovy.lang.Closure)
    at Main$Child.methodMissing(test.groovy)
    at Main$Child$_foo_closure1.doCall(test.groovy:16)
    at Main$Child$_foo_closure1.doCall(test.groovy)
    at Main$Child.foo(test.groovy:23)
    at Main$Child$foo.call(Unknown Source)
    at Main.main(test.groovy:3)

Как я могу сослаться на метод суперкласса (Parent.foo) из замыкания (myClosure), заключенного в соответствующий метод подкласса (Child.foo)?

(справочная информация: замыкание в моем реальном коде необходимо для выполнения чего-то вроде myCloseable.withCloseable { super.foo(); … })

1 Ответ

0 голосов
/ 18 февраля 2019

как только закрытие - это другой класс (с точки зрения java), и вы не можете получить доступ к методу super из другого класса.

IHMO единственный путь:

class Main {
  public static void main(String ... args) {
    new Child().foo()
  }

  public static class Parent {
    def foo() {
      println 'from parent'
    }
  }

  public static class Child extends Parent {
    def superFoo(){
        super.foo()
    }
    def foo() {
      def myClosure = {
        superFoo()
        println 'from child'
      }
      myClosure()
    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...