Skip to content

Instantly share code, notes, and snippets.

@latant
Last active April 19, 2019 21:19
Show Gist options
  • Save latant/2255cbe514157e31dc9f57d39528ecf3 to your computer and use it in GitHub Desktop.
Save latant/2255cbe514157e31dc9f57d39528ecf3 to your computer and use it in GitHub Desktop.
Example of logging method calls in groovy with Interceptor and ProxyMetaClass
class DeterminantTeller {
Double tellToQuadratic(Double a, Double b, Double c) { b ** 2 - 4 * a * c }
}
class Solver {
def teller = new DeterminantTeller()
List<Double> solveQuadratic(Double a, Double b, Double c) {
def determinant = teller.tellToQuadratic(a, b, c)
if (determinant < 0) return []
def sqrtDeterminant = Math.sqrt(determinant)
def minusB = -b
def twoA = 2 * a
return [
(minusB + sqrtDeterminant) / twoA,
(minusB - sqrtDeterminant) / twoA
]
}
}
class LoggerInterceptor implements Interceptor {
final static Integer TAB_LENGTH = 2
static Integer tabCount = 0
static String indentation() { " ".repeat(TAB_LENGTH * tabCount) }
Object beforeInvoke(Object object, String name, Object[] args) {
println "${indentation()}<$object>.$name(${args.join(',')})"
tabCount++
null
}
Object afterInvoke(Object object, String name, Object[] args, Object result) {
tabCount--
println "${indentation()}return $result"
result
}
boolean doInvoke() { true }
}
class ProxySet {
final static loggerInterceptor = new LoggerInterceptor()
List<ProxyMetaClass> proxies
ProxySet(Class... classes) {
proxies = classes.collect {
ProxyMetaClass.getInstance(it).tap {
interceptor = loggerInterceptor
}
}
}
def use(Closure closure) { use(0, closure) }
def use(Integer proxyIndex, Closure closure) {
def proxy = proxies[proxyIndex]
if (proxyIndex == proxies.size() - 1)
proxy.use { closure() }
else
proxy.use { this.use(++proxyIndex, closure) }
}
}
def proxySet = new ProxySet(DeterminantTeller, Solver)
proxySet.use {
def solver = new Solver()
solver.solveQuadratic(2, 10, 4)
}
/**
* <class Solver>.ctor()
* <class DeterminantTeller>.ctor()
* return DeterminantTeller@797501a
* return Solver@1a15b789
* <Solver@1a15b789>.solveQuadratic(2,10,4)
* <DeterminantTeller@797501a>.tellToQuadratic(2.0,10.0,4.0)
* return 68.0
* return [-0.4384471871911697, -4.561552812808831]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment