簡體   English   中英

Groovy:如何在子類方法中從閉包引用超類方法?

[英]Groovy: How to Refer to a Super Class Method from a Closure in a Subclass Method?

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

一旦關閉-它是另一個類(就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()
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM