Added get(key, type) method to Cache interface

This new get variant not only allows for generically specifying the required value type; it also skips the ValueWrapper that the standard get method returns. Note that it is not possible to differentiate between non-existing cache entries and cached null values that way; for that purpose, the standard get variant needs to be used.

Issue: SPR-11061
This commit is contained in:
Juergen Hoeller
2013-11-04 14:31:41 +01:00
parent b093b84954
commit 50d3f71923
9 changed files with 81 additions and 14 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,6 +65,17 @@ public class EhCacheCache implements Cache {
return (element != null ? new SimpleValueWrapper(element.getObjectValue()) : null);
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(Object key, Class<T> type) {
Element element = this.cache.get(key);
Object value = (element != null ? element.getObjectValue() : null);
if (type != null && !type.isInstance(value)) {
throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
}
return (T) value;
}
@Override
public void put(Object key, Object value) {
this.cache.put(new Element(key, value));

View File

@@ -82,6 +82,16 @@ public class JCacheCache implements Cache {
return (value != null ? new SimpleValueWrapper(fromStoreValue(value)) : null);
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(Object key, Class<T> type) {
Object value = fromStoreValue(this.cache.get(key));
if (type != null && !type.isInstance(value)) {
throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value);
}
return (T) value;
}
@Override
@SuppressWarnings("unchecked")
public void put(Object key, Object value) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,6 +62,11 @@ public class TransactionAwareCacheDecorator implements Cache {
return this.targetCache.get(key);
}
@Override
public <T> T get(Object key, Class<T> type) {
return this.targetCache.get(key, type);
}
@Override
public void put(final Object key, final Object value) {
if (TransactionSynchronizationManager.isSynchronizationActive()) {