Dynamic Proxy (#1702)
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
594920af9b
commit
772002f3ad
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.dynamicproxy;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
public class DynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(DynamicInvocationHandler.class);
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
LOGGER.info("Invoked method: {}", method.getName());
|
||||
|
||||
return 42;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.dynamicproxy;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class TimingDynamicInvocationHandler implements InvocationHandler {
|
||||
|
||||
private static Logger LOGGER = LoggerFactory.getLogger(TimingDynamicInvocationHandler.class);
|
||||
private final Map<String, Method> methods = new HashMap<>();
|
||||
|
||||
private Object target;
|
||||
|
||||
public TimingDynamicInvocationHandler(Object target) {
|
||||
this.target = target;
|
||||
|
||||
for(Method method: target.getClass().getDeclaredMethods()) {
|
||||
this.methods.put(method.getName(), method);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
long start = System.nanoTime();
|
||||
Object result = methods.get(method.getName()).invoke(target, args);
|
||||
long elapsed = System.nanoTime() - start;
|
||||
|
||||
LOGGER.info("Executing {} finished in {} ns", method.getName(), elapsed);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user