I can get exactly the same result as the expected output. Thanks.
package com.codegym.task.task34.task3408;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.WeakHashMap;
public class Cache<K, V> {
private Map<K, V> cache = new WeakHashMap<>(); // TODO: Add your code here
public V getByKey(K key, Class<V> clazz) throws Exception {
// TODO: Add your code here
V value = cache.get(key);
if (value == null) {
Constructor ctor = clazz.getDeclaredConstructor(key.getClass());
value = (V) ctor.newInstance(key);
cache.put(key, value);
}
return value;
}
public boolean put(V obj) {
// TODO: Add your code here
try {
Method method = obj.getClass().getMethod("getKey", null);
method.setAccessible(true);
K key = (K) method.invoke(obj, null);
cache.put(key, obj);
return true;
} catch (NoSuchMethodException e) {
return false;
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException e) {
return false;
}
}
public int size() {
return cache.size();
}
}