2017-02-17 17 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! –