简体   繁体   中英

How to cache result for a function with variable arguments (Varargs) in Java

I have Java method like this:

  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 .

What you can can do is to encapsulate these objects into a class, say, 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 .
Note : objects is an array, so you have to use Arrays.equals() method to compare it.

And finally, create a HashMap with your MyKey class as a key and the cached value as the map's value:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM