1

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
    }
}


  • 1
    That is a standard return value for a Map - if the key you are putting did not exist then return null. What are you expecting to get returned and why? – takendarkk May 17 '19 at 18:43

2 Answers2

2

To quote the documentaion, Map#put retruns "the previous value associated with key, or null if there was no mapping for key". Since this is the first time you introduce the key 0 to the map, the return value of put(0, "value-0") is indeed null. You would get the same result if the map wasn't proxied.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

This is expected - put returns the previous value on the map, or null if it doesn't exist

See from javadoc:
Returns: the previous value associated with key, or null if there was no mapping for key.

Nir Levy
  • 12,750
  • 3
  • 21
  • 38