1

我有如下示例代码

import org.codehaus.groovy.control.CompilerConfiguration

abstract class MyClass extends Script {

    void testMethod(Integer x) {
        println "x = $x"
    }
}

public static void main(String[] args) {
    compilerConfiguration = new CompilerConfiguration();
    compilerConfiguration.setScriptBaseClass("MyClass");
    GroovyShell shell = new GroovyShell(new Binding(), compilerConfiguration);
    shell.evaluate("testMethod 1")
}

x = 1 当我运行这个类时,如果我将它更改"testMethod 1"为它现在打印"testMethod -1"它失败了

Caught: groovy.lang.MissingPropertyException: No such property: testMethod for class: Script1
groovy.lang.MissingPropertyException: No such property: testMethod for class: Script1
    at Script1.run(Script1.groovy:1)
    at Test.run(Test.groovy:15)

现在我"testMethod -1"改为"testMethod (-1)". 它再次工作并打印x = -1

我需要了解的是为什么 Groovy 要求括号中的负数。

4

1 回答 1

1

因为没有括号,它假设您正在尝试从名为testMethod(ie: testMethod - 1)的属性中减去 1

您需要括号来通知解析器这是一个方法调用而不是减法运算


编辑

我想出了一个可怕的方法来让它工作:

import java.lang.reflect.Method
import org.codehaus.groovy.control.CompilerConfiguration

abstract class MyClass extends Script {
  private methods = [:]
  
  class MinusableMethod {
    Script declarer
    Method method
    MinusableMethod( Script d, Method m ) {
      this.declarer = d
      this.method = m
    }
    def minus( amount ) {
      method.invoke( declarer, -amount )
    }
  }

  public MyClass() {
    super()
    methods = MyClass.getDeclaredMethods().grep {
      it.name != 'propertyMissing' && !it.synthetic
    }.collectEntries {
      [ (it.name): new MinusableMethod( this, it ) ]
    } 
  }

  def propertyMissing( String name ) {
    methods[ name ]
  }

  void testMethod(Integer x) {
      println "x = $x"
  }
}

static main( args ) {
  def compilerConfiguration = new CompilerConfiguration();
  compilerConfiguration.setScriptBaseClass( 'MyClass' );
  GroovyShell shell = new GroovyShell(new Binding(), compilerConfiguration);
  shell.evaluate("testMethod - 1")
}

但这可能会在其他条件下中断

从长远来看,让人们编写有效的脚本可能是更好的途径……

于 2012-05-16T14:41:00.020 回答