2016-12-29 62 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

相关问题