import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; public class Cache { private final int capacity; private final Map cache; public Cache(int capacity) { this.capacity = capacity; this.cache = new HashMap<>(); } public void put(K key, V value) { if (key == null) { return; } if (cache.size() >= capacity && !cache.containsKey(key)) { K oldestKey = cache.keySet().iterator().next(); cache.remove(oldestKey); } cache.put(key, value); } public V get(K key) { return cache.get(key); } public void remove(K key) { cache.remove(key); } public void clear() { cache.clear(); } public int getCapacity() { return capacity; } public int getSize() { return cache.size(); } public boolean containsKey(K key) { return cache.containsKey(key); } @SuppressWarnings("unchecked") public Class getKeyType() { Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; Type[] typeArgs = paramType.getActualTypeArguments(); if (typeArgs != null && typeArgs.length > 0 && typeArgs[0] instanceof Class) { return (Class) typeArgs[0]; } } return null; } @SuppressWarnings("unchecked") public Class getValueType() { Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) type; Type[] typeArgs = paramType.getActualTypeArguments(); if (typeArgs != null && typeArgs.length > 1 && typeArgs[1] instanceof Class) { return (Class) typeArgs[1]; } } return null; } @Override public String toString() { return "Cache{" + "capacity=" + capacity + ", cache=" + cache + '}'; } }