[英]How to cache result for a function with variable arguments (Varargs) in Java
I have Java method like this: 我有这样的Java方法:
public <T> T queryDB(Class<T> klass, Object... objects) {
return dbClient.get(klass, objects);
}
How can I cache this call? 如何缓存此呼叫? It is using variable arguments.
它使用可变参数。 I am not sure how to correctly build a cache key?
我不确定如何正确构建缓存键?
If you return some value based on your klass
and object
variables that means you have a composite key of klass
and object
. 如果您基于
klass
和object
变量返回一些值,则意味着您具有klass
和object
的复合键。
What you can can do is to encapsulate these objects into a class, say, MyKey
: 您可以做的就是将这些对象封装到一个类中,例如
MyKey
:
public class MyKey <T> {
Class<T> klass;
Object[] objects;
public MyKey(Class<T> klass, Object... objects) {
this.klass = klass;
this.objects = objects;
}
@Override
public boolean equals(Object obj) {
//implement this method comparing klass and objects
}
@Override
public int hashCode() {
//calculate a hash based on klass and objects' hashes
}
}
Override equals()
and hashCode()
methods of this class (mandatory!) that calculate their values based on klass
and objects variables
. 覆盖此类的强制
equals()
和hashCode()
方法(强制!),这些方法基于klass
和objects variables
计算其值。
Note : objects
is an array, so you have to use Arrays.equals()
method to compare it. 注意 :
objects
是一个数组,因此必须使用Arrays.equals()
方法进行比较。
And finally, create a HashMap
with your MyKey
class as a key and the cached value as the map's value: 最后,创建一个
HashMap
其中将MyKey
类作为键,并将缓存的值作为地图的值:
Map<MyKey<T>, T> cache = new HashMap<>();
Each time you want to check if the value is hashed, call 每次您要检查该值是否为哈希值时,请调用
cache.get(new MyKey(klass, objects));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.