There is a problem when method invoke is called for the method- 'V put(K key, V val)' from proxied Map it returns null. But for the method - V get(K key) it is all right.
See code example
package com.dynamic.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LogHandler implements InvocationHandler {
private final Object target;
public LogHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Start");
Object o = method.invoke(target, args);
System.out.println("Finish");
return o;
}
}
-----
package com.dynamic.proxy;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
LogHandler logHandler = new LogHandler(new HashMap<>());
Map<Integer, String> map =
(Map) Proxy.newProxyInstance(logHandler.getClass().getClassLoader(),
new Class[]{Map.class},
logHandler);
System.out.println(map.put(0, "value-0")); //null
System.out.println(map.get(0)); // value-0
}
}