Es posible añadir nuevos constructores o reemplazar el antiguo. Si necesita el constructor original, puede utilizar la reflexión para que:
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
}
Tenga en cuenta que usted tiene que cambiar esto si tiene parámetros a los constructores, por ejemplo:
// 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: Tenga en cuenta que cuando Si desea agregar constructores que aún no existen, utilice el operador <<
en su lugar: MyObject.metaClass.constructor << { /* as above */ }
.
nunca hizo eso a mí mismo, pero esto podría ayudar a http://groovy.codehaus.org/ExpandoMetaClass+-+Constructors –
enlace excelente, gracias –