2017-02-17 19 views
0

创建方法的名称目前,我有以下代码:如何动态地在常规

class SampleFixture { 

    static aFixtureWithCodeAA() { 
     fixtureAA() 
    } 

    static aFixtureWithCodeBB() { 
     fixtureBB() 
    } 

    static aFixtureWithCodeCC() { 
     fixtureCC() 
    } 
} 

我想将它变换成这个喜欢

class SampleFixture { 

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

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

我该怎么做?

编辑:我一直在阅读这http://groovy-lang.org/metaprogramming.html#_dynamic_method_names,它看起来像我想要做的,但我似乎无法得到它的工作。

只是为了澄清:在阅读本文之后,我想最终得到的是一个带有baseName + varSufix的方法,如“fixture $ {code}”()中所示。理想的情况是我最终会是这样的:

class SampleFixture { 

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

所以我不得不依赖于我传递的代码不同的方法名。

回答

0

您可以实现一个方法叫做invokeMethod(String method, args)method参数解析代码:

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" 

UPDATE:下面是使用第二类的方法调用重定向到另一个类

的解决方案
class Fixture { 
    def fixtureAA() { "code aa" } 
    def fixtureBB() { "code bb" } 
    def fixtureCC() { "code cc" } 
} 

class SampleFixture {} 

SampleFixture.metaClass.static.invokeMethod = { String method, args -> 
    def code = method - "aFixtureWithCode" 
    new Fixture()."fixture${code}"() 
} 


assert SampleFixture.aFixtureWithCodeAA() == "code aa" 
assert SampleFixture.aFixtureWithCodeBB() == "code bb" 
assert SampleFixture.aFixtureWithCodeCC() == "code cc" 
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() 
+0

这正是我一直在寻找。这工作。 TY! –