Гонял дебагером, метод get добавляет объект, если нет требуемого объекта в кэше.
put извлекает key и добавляет пару key, value. А что-то всё равно не нравится. А что не пойму?
package com.javarush.task.task34.task3408;
import java.lang.reflect.Field;
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<K, V>(); //TODO add your code here
public V getByKey(K key, Class<V> clazz) throws Exception {
//TODO add your code here
V tmp = cache.get(key);
if ( tmp != null) return tmp;
else{
Object obj = clazz.newInstance();
V newRef = (V) obj;
Field fieldKey = clazz.getDeclaredField("myKey");
fieldKey.setAccessible(true);
fieldKey.set(newRef, key);
cache.put(key, newRef);
return cache.get(key);
//return null;
}
}
public boolean put(V obj) /*throws NoSuchMethodException, InvocationTargetException, IllegalAccessException*/ {
//TODO add your code here
try{
Class clazz = obj.getClass();
Method method = clazz.getDeclaredMethod("getKey");
method.setAccessible(true);
Solution.SomeKey key = (Solution.SomeKey) method.invoke(obj);
cache.put((K) key, obj);
return true;
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e){
return false;
}
}
public int size() {
return cache.size();
}
}