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(すなわち:)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 に答える