anish
anish

Reputation: 7412

groovy singleton to access overloaded constructor

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)

Upvotes: 0

Views: 2665

Answers (1)

ataylor
ataylor

Reputation: 66079

In the first case you are accessing the static property test.instance, which in turn calls the static method test.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 the new 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.

Upvotes: 6

Related Questions