2016-12-29 61 views
4

我有以下的Groovy類:吉斯,Groovy中,@Canonical和繼承沒有很好地一起玩

enum Protocol { 
    File, 
    Ftp, 
    Sftp, 
    Http, 
    Https 
} 

@Canonical 
abstract class Endpoint { 
    String name 
    Protocol protocol 
} 

@Canonical 
@TupleConstructor(includeFields=true, includeSuperFields=true) 
class LocalEndpoint extends Endpoint { 
} 

class MyAppModule extends AbstractModule { 
    @Override 
    protected void configure() { 
     // Lots of stuff... 
    } 

    // Lots of other custom providers 

    @Provides 
    Endpoint providesEndpoint() { 
     new LocalEndpoint('fileystem', Protocol.File) 
    } 
} 

不要擔心,爲什麼我使用的Endpoint,而不是隻自定義提供:

bind(Endpoint).toInstance(new LocalEndpoint('fileystem', Protocol.File)) 

我99.999%肯定這是超出這個問題,並編碼的方式,因爲如何完整(非常大)的代碼連線。

我的問題是,吉斯和/或Groovy找不到LocalEndpoint一個構造函數一個StringProtocol說法:

1) Error in custom provider, groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.example.myapp.model.LocalEndpoint(java.lang.String, com.example.myapp.model.Protocol) 
    at com.example.myapp.inject.MyAppModule.providesEndpoint(MyAppModule.groovy:130) 
    while locating com.example.myapp.model.Endpoint 
    for parameter 2 at com.example.myapp.inject.MyAppModule.providesConfig(MyAppModule.groovy:98) 
    at com.example.myapp.inject.MyAppModule.providesConfig(MyAppModule.groovy:98) 
    while locating com.example.myapp.config.MyAppConfig 

然後吐出來跟下面列出的原因大堆棧跟蹤:

Caused by: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.example.myapp.model.LocalEndpoint(java.lang.String, com.example.myapp.model.Protocol) 
     at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1731) 
     at groovy.lang.MetaClassImpl.invokeConstructor(MetaClassImpl.java:1534) 

但願這東西,我可以通過修改Endpoint和/或LocalEndpoint調整,也許我需要一些特殊的參數傳遞到@Canonical/@TupleConstructor註釋什麼的。有任何想法嗎?

+2

資格參數在構造函數new LocalEndpoint(name:'fileystem',protocol:Protocol.File) –

+0

謝謝@ToddWCrone(+1)但我不喜歡Groovy映射構造函數。感謝'@ Canonical','@ TupleConstructor'等等,我應該能夠使用普通的「Java風格」構造函數調用。任何建議如何獲得這個工作無效的地圖構造函數?再次感謝! – smeeb

+0

合格的參數名稱更好。我不會花費很多精力去嘗試讓更模糊的構造函數工作。抱歉。 –

回答

3

我認爲你需要在TupleConstructor添加註釋includeSuperProperties,這似乎解決它,甚至本身:

@TupleConstructor(includeSuperProperties=true)

所以整個事情將是:

@Canonical 
abstract class Endpoint { 
    String name 
    Protocol protocol 
} 

@Canonical // You may not need this anymore 
@TupleConstructor(includeSuperProperties=true) 
class LocalEndpoint extends Endpoint { 
} 
+0

Thanks @Igor(+1) - ** that worked !!! **在我可以獎勵你獎金之前,有一個快速跟進問題:以前我有'includeSuperFields = true'設置。爲什麼(在我的具體情況下)是否包含SuperProperties工作,但不包括* includeSuperFields?何時何地使用每種產品有何區別?再次感謝!! – smeeb

+0

@smeeb是的,這是一個奇怪的行爲。我期望'includeSuperProperties'捕獲的任何東西都可以在'includeSuperFields'中獲得任何東西。這個文檔也不太詳細,所以我不確定。您最好的選擇可能是查看實現: - \ – Igor

相關問題