Quantcast

Override a method without knowing its parameters

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Override a method without knowing its parameters

Douglas Mendes
Hi.

How can I properly override a method given a java.lang.reflect.Method and its respective MetaClass?

I know that can be achieved by overriding the MetaClass's invokeMethod but I can't do that (even if I could, would like to avoid).

Pseudocode:

void doAnOverride(MetaClass metaClass, Method method) {
    metaClass."${method.name}" = { args ->
        println "done"
    }
}

Thanks,
Douglas
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Override a method without knowing its parameters

Douglas Mendes
Answering my own question:

It can be done if the metaClass is an ExpandoMetaClass. Like this:

expandoMetaClass.registerInstanceMethod(
    new TransformMetaMethod(originalMetaMethod) {
        @Override
        Object invoke(Object object, Object[] arguments) {
            println "Done! Method overriden!"
            super.invoke(object, arguments)
        }
    }
)

Anyway, in grails it didn't work (it kept calling the original method). Had to use an AST.

Regards,
Douglas

Em qui, 23 de fev de 2017 às 16:12, Douglas Mendes <[hidden email]> escreveu:
Hi.

How can I properly override a method given a java.lang.reflect.Method and its respective MetaClass?

I know that can be achieved by overriding the MetaClass's invokeMethod but I can't do that (even if I could, would like to avoid).

Pseudocode:

void doAnOverride(MetaClass metaClass, Method method) {
    metaClass."${method.name}" = { args ->
        println "done"
    }
}

Thanks,
Douglas
Loading...