Skip to content

Commit

Permalink
当返回值为数组时,使用Array.newInstance创建数组,magic模式下,生成缓存key个数为0时返回空的集合
Browse files Browse the repository at this point in the history
  • Loading branch information
qiujiayu committed Jul 12, 2019
1 parent 52b74df commit c99cfb9
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/main/java/com/jarvis/cache/MagicHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,24 @@ public static boolean isMagic(Cache cache, Method method) throws Exception {
private Collection<Object> newCollection(Class<?> collectionType, int resSize) throws Exception {
Collection<Object> res;
if (LinkedList.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptyList();
}
res = new LinkedList<>();
} else if (List.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptyList();
}
res = new ArrayList<>(resSize);
} else if (LinkedHashSet.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptySet();
}
res = new LinkedHashSet<>(resSize);
} else if (Set.class.isAssignableFrom(collectionType)) {
if (resSize == 0) {
return Collections.emptySet();
}
res = new HashSet<>(resSize);
} else {
throw new Exception("Unsupported type:" + collectionType.getName());
Expand All @@ -154,6 +166,12 @@ public Object magic() throws Throwable {
return newValue;
}
Map<CacheKeyTO, Object> keyArgMap = getCacheKeyForMagic();
if (null == keyArgMap || keyArgMap.isEmpty()) {
if (returnType.isArray()) {
return Array.newInstance(returnType.getComponentType(), 0);
}
return newCollection(returnType, 0);
}
Type returnItemType = getRealReturnType();
Map<CacheKeyTO, CacheWrapper<Object>> cacheValues = this.cacheHandler.mget(method, returnItemType, keyArgMap.keySet());
// 如果所有key都已经命中
Expand Down Expand Up @@ -276,14 +294,14 @@ private Object convertToReturnObject(Map<CacheKeyTO, CacheWrapper<Object>> cache
Object[] newValues = (Object[]) newValue;
resSize = cacheValues.size() + (null == newValues ? 0 : newValues.length);
}
Object[] res = new Object[resSize];
Object res = Array.newInstance(returnType.getComponentType(), resSize);
int ind = 0;
for (CacheKeyTO cacheKeyTO : cacheKeys) {
Object val = getValueFormCacheOrDatasource(cacheKeyTO, cacheValues, unmatchCache);
if (!magic.returnNullValue() && null == val) {
continue;
}
res[ind] = val;
Array.set(res, ind, val);
ind++;
}
return res;
Expand Down Expand Up @@ -363,9 +381,6 @@ private Map<CacheKeyTO, Object> getCacheKeyForMagic() {
cacheKeys[ind] = cacheKeyTO;
}
}
if (null == keyArgMap || keyArgMap.isEmpty()) {
throw new IllegalArgumentException("the 'keyArgMap' is empty");
}
return keyArgMap;
}

Expand Down

0 comments on commit c99cfb9

Please sign in to comment.