È possibile aggiungere nuovi costruttori o sostituire quello vecchio. Se è necessario il costruttore originale, è possibile utilizzare la riflessione per questo:
MyObject.metaClass.constructor = { -> // for the no-arg ctor
// use reflection to get the original constructor
def constructor = MyObject.class.getConstructor()
// create the new instance
def instance = constructor.newInstance()
// ... do some further stuff with the instance ...
println "Created ${instance}"
instance
}
Nota che devi cambiare questo se si dispone dei parametri ai costruttori, per esempio:
// Note that the closure contains the signature of the constructor
MyObject.metaClass.constructor = { int year, String reason ->
def constructor = MyObject.class.getConstructor(Integer.TYPE, String.class)
def instance = constructor.newInstance(
2014, "Boy, am I really answering a question three years old?")
// ... do some further stuff with the instance ...
println "Created ${instance}"
instance
}
PS: Si noti che quando vuoi aggiungere costruttori che non sono ancora esistenti, usa invece l'operatore <<
: MyObject.metaClass.constructor << { /* as above */ }
.
mai fatto io stesso, ma questo potrebbe aiutare http://groovy.codehaus.org/ExpandoMetaClass+-+Constructors –
collegamento eccellente, grazie –