aspose file tools*
The moose likes Groovy and the fly likes Intercepting Constructors and The Calling Original Constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Languages » Groovy
Bookmark "Intercepting Constructors and The Calling Original Constructor" Watch "Intercepting Constructors and The Calling Original Constructor" New topic
Author

Intercepting Constructors and The Calling Original Constructor

Ivan Krizsan
Ranch Hand

Joined: Oct 04, 2006
Posts: 2198
    
    1
Hi!
I want to intercept a constructor of a class and successfully does that by using the following technique:

When intercepting regular and dynamically added methods, I do this to obtain the MetaMethod object and invoke the original method:

However, when intercepting constructors, I am not able to successfully use the above technique.
Most of the time trying to invoke the intercepted constructor, I end up intercepting the call from the intercepting code and thus causing an infinite loop.
My question is:
Does anyone know how I should invoke the original constructor that I intercept from the intercepting code, without intercepting this call?
Many thanks in advance!
Ivan Krizsan
Ranch Hand

Joined: Oct 04, 2006
Posts: 2198
    
    1
Hi Ivan!
You can implement a subclass of DelegatingMetaClass, in which you implement the invokeConstructor method.
Then you create an instance of your metaclass supplying the class you want to intercept constructor calls on as a parameter.
Finally, you register the metaclass instance in the meta registry, again for the class which you want to intercept constructor calls.
In the invokeConstructor, you simply call super.invokeConstructor to call the original constructor and retrieve an instance of the intercepted class.
Be aware that if you, for instance, add a method dynamically to, for instance, an instance of the class for which constructors are to be intercepted, the metaclass in that particular instance will be replaced by an instance of ExpandoMetaClass and the interception will no longer take place.
Making further investigations - perhaps I will be able to come up with a solution that allows interception of constructors and adding methods dynamically.
Best wishes!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Intercepting Constructors and The Calling Original Constructor