summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/collections/MethodCache.java
blob: 252199ad5c85ec20b7fa25ea5f302795f9beb5a8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.collections;

import com.yahoo.concurrent.CopyOnWriteHashMap;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author baldersheim
 */
public final class MethodCache {
    private final String methodName;
    private final CopyOnWriteHashMap<String, Method> cache = new CopyOnWriteHashMap<>();

    public MethodCache(String methodName) {
        this.methodName = methodName;
    }

    public final Method get(Object object) {
        Method m = cache.get(object.getClass().getName());
        if (m == null) {
            m = lookupMethod(object);
            if (m != null) {
                cache.put(object.getClass().getName(), m);
            }
        }
        return m;
    }
    private Method lookupMethod(Object object)  {
        try {
            return object.getClass().getMethod(methodName);
        } catch (NoSuchMethodException e) {
            return null;
        }
    }
}