DevOps / Apache Groovy Interview questions
Explain the lifecycle of a Groovy Category being applied with use()?
A Category is an ordinary Groovy or Java class containing static methods, each written with the "extended" type as the first parameter - for example a static method String reversed(String self) defines a reversed() method that appears to be added onto String, but only within a specific scope, not permanently.
Calling use(SomeCategory) { ... } temporarily registers that Category's static methods onto the metaClass lookup chain for the duration of the closure passed to use, scoped specifically to the current thread executing that block - it doesn't globally or permanently modify the target classes' metaClass the way a direct metaClass assignment would.
Inside that closure, any call matching one of the Category's method signatures by first-parameter type resolves to the Category's static method, with self bound to the actual receiver object the method was called on - to code inside the block, it looks exactly like an ordinary instance method call.
Once the use block's closure finishes executing, the Category's methods are automatically deregistered from the lookup chain - calling the same method again outside the block, even on the same object, fails to resolve, since the temporary registration was scoped strictly to that block's execution.
This makes Categories well suited to safely and temporarily extending even classes you don't own, like adding a method to String, for a specific, bounded piece of code, without risking that extension leaking out and unexpectedly changing behavior elsewhere in the application.
flowchart LR A[use SomeCategory closure] --> B[Register Category's static methods on lookup chain] B --> C[Calls inside block resolve to Category methods] C --> D[Block finishes executing] D --> E[Category methods automatically deregistered]
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
