groovy 单例访问重载构造函数
groovy Singleton(注意,在 Groovy 2.6 中,如果要包含显式构造函数,则必须将 strict 设置为 false)
@Singleton( strict = false )
class test {
private test(){
//some Method call
}
private test(def x){
//some Method call
}
}
test.groovy
def test1 = test.instance
当我发出以下语句时,它对我有用,我可以看到默认值 构造函数被调用,
我如何在使用第二个构造函数参数时创建实例
如果我发出它,
def test2 = test("anish").instance
,它会抛出错误,我该如何解决这个任何建议
groovy.lang.MissingMethodException: No signature of method: test.test() is applicable for argument types: (java.lang.String) values: [anish]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:54)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:78)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:143)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:151)
groovy Singleton (NB at Groovy 2.6 you must set strict to false if you want to include the explicit constructor)
@Singleton( strict = false )
class test {
private test(){
//some Method call
}
private test(def x){
//some Method call
}
}
test.groovy
def test1 = test.instance
when i issue the following statement it works for me and i can see the defualt
constructor is called
how can i create instanace while using second construcor argument
if i issue
def test2 = test("anish").instance
it throws me error how do i resolve this any suggestion
groovy.lang.MissingMethodException: No signature of method: test.test() is applicable for argument types: (java.lang.String) values: [anish]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:54)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:78)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:143)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:151)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在第一种情况下,您访问静态属性
test.instance
,该属性又调用静态方法test.getInstance()
。在第二种情况下,您似乎正在尝试将第二个构造函数作为方法调用。这不是有效的常规:您需要使用 new 关键字来创建一个实例,该实例会触发构造函数。此外,将构造函数设置为私有会使其无法访问,除非在类本身内。如果您需要实例化另一个实例,它可能首先不应该是单例。
In the first case you are accessing the static property
test.instance
, which in turn calls the static methodtest.getInstance()
. In the second case, it looks like you are trying to call the second constructor as a method. That's not valid groovy: you need to use thenew
keyword to create an instance, which triggers the constructor. Also, making the constructor private makes it inaccessible except within the class itself.If you need to instantiate another instance, it probably shouldn't be a singleton in the first place.