如何在groovy中动态创建方法名称

时间:2017-02-17 15:17:09

标签: groovy

目前我有以下代码:

class SampleFixture {

    static aFixtureWithCodeAA() {
        fixtureAA()
    }

    static aFixtureWithCodeBB() {
        fixtureBB()
    }

    static aFixtureWithCodeCC() {
        fixtureCC()
    }
}

我希望将其转换为类似

的内容
class SampleFixture {

    static aFixture(code) {
        fixture[code]()
    }
}

我有另一个类,其中定义了fixtureAA,fixtureBB和fixtureCC。所以代码值是预定义的。我希望方法fixture [code]在运行时构建,而不是为每个夹具都有一个方法。

我该怎么做?

编辑:我一直在阅读http://groovy-lang.org/metaprogramming.html#_dynamic_method_names这看起来像我想做的事情,但我似乎无法让它发挥作用。

只是为了澄清:在阅读本文之后,我最终想要的是一个带有baseName + varSufix的方法,如" fixture $ {code}"()。理想情况下,我最终会得到类似的东西:

class SampleFixture {

    static aFixture(code) {
        MyClass."fixture{code}"()
    }
}

所以我根据我传递的代码有不同的方法名称。

2 个答案:

答案 0 :(得分:1)

你的意思是:

class MyClass {
    static fixtureAA() { "oooh, aa" }
    static fixtureBB() { "cool, bb" }
    static fixtureCC() { "wow,  cc" }
}

class MyFixture {
    def call(code) {
        MyClass."fixture$code"()
    }
}

println new MyFixture().call('BB')

(你太近了)

或者,您可以执行以下操作:

class MyClass {
    static fixtureAA() { "oooh, aa" }
    static fixtureBB() { "cool, bb" }
    static fixtureCC() { "wow,  cc" }
}

class MyFixture {
    def methodMissing(String name, args) {
        try {
            MyClass."fixture$name"()
        }
        catch(e) {
            "No idea how to $name"
        }
    }
}

assert "oooh, aa" == new MyFixture().AA()
assert "cool, bb" == new MyFixture().BB()
assert "wow,  cc" == new MyFixture().CC()
assert "No idea how to DD" == new MyFixture().DD()

答案 1 :(得分:0)

您可以实现一个名为invokeMethod(String method, args)的方法并解析string="SELECT * FROM {token1} WHERE {token2}"; ["SELECT","*"," ","FROM","WHERE","{",].forEach(el=>string=string.split(el).join("")); MyArr=string.split("}"); 参数中的代码:

method

UPDATE:这是使用第二个类将方法调用重定向到另一个类的解决方案

class SampleFixture {

    def fixture = [
        AA: { "code aa" },
        BB: { "code bb" },
        CC: { "code cc" },
    ]

    def invokeMethod(String method, args) {
        def code = method - "aFixtureWithCode"
        fixture[code]()
    }
}


f = new SampleFixture()

assert f.aFixtureWithCodeAA() == "code aa"
assert f.aFixtureWithCodeBB() == "code bb"
assert f.aFixtureWithCodeCC() == "code cc"
相关问题