groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Eric MacAdie <emaca...@gmail.com>
Subject Intercepting Constructors for ArrayList
Date Mon, 08 Jun 2015 04:32:36 GMT
Has anyone ever tried to intercept the constructors for ArrayList?

I would like to intercept them, and call asImmutable() on them, to be a bit
more functional. And just general curiosity.

According to the shell, there are three constructors for ArrayList:

groovy:000> ArrayList.class.getConstructors()
===> [public java.util.ArrayList(java.util.Collection), public
java.util.ArrayList(), public java.util.ArrayList(int)]


I have been able to write code to intercept the null and the int:

java.util.ArrayList.metaClass.constructor = {  ->
    println "Intercepting constructor call"
    constructor = ArrayList.class.getConstructor( null )
    constructor.newInstance(  ).asImmutable()
}

java.util.ArrayList.metaClass.constructor = { int arg ->
    println "Intercepting int constructor call"
    constructor = ArrayList.class.getConstructor( int )
    constructor.newInstance( arg ).asImmutable()
}

But I cannot figure out how to intercept the
java.util.ArrayList(java.util.Collection). Here are a couple of attempts:

java.util.ArrayList.metaClass.constructor = { java.util.Collection arg ->
    println "Intercepting Collection call, here is arg: ${arg.class.name}"
    constructor = ArrayList.class.getConstructor( java.util.Collection )
    println "just made constructor: ${constructor}"
    constructor.newInstance( arg ).asImmutable()
}

java.util.ArrayList.metaClass.constructor = {  Object[] arg ->
    println "Intercepting Second Collection call"
    constructor = ArrayList.class.getConstructor( java.util.Collection )
    println "just made constructor: ${constructor}"
    constructor.newInstance( arg ).asImmutable()
}

I can intercept the java.util.Collection constructor with a closure, but I
would like to be able to get it with metaprogramming.

def collConst = ArrayList.class.getConstructor( java.util.Collection )
def constQ = { Object[] args -> collConst.newInstance( args ).asImmutable()
}
def firstQ = constQ( [ 1, 2, 3, "kkkkk" ] )

= Eric MacAdie

Mime
View raw message