WitnessClassFinder.java 1.5 KB
Newer Older
1 2 3
package org.skywalking.apm.agent.core.plugin;

import java.util.Map;
wu-sheng's avatar
wu-sheng 已提交
4
import java.util.HashMap;
5 6 7 8 9 10 11 12 13 14 15 16
import net.bytebuddy.pool.TypePool;

/**
 * The <code>WitnessClassFinder</code> represents a pool of {@link TypePool}s,
 * each {@link TypePool} matches a {@link ClassLoader},
 * which helps to find the class define existed or not.
 *
 * @author wusheng
 */
public enum WitnessClassFinder {
    INSTANCE;

wu-sheng's avatar
wu-sheng 已提交
17
    private Map<ClassLoader, TypePool> poolMap = new HashMap<ClassLoader, TypePool>();
18 19 20 21 22 23 24 25

    /**
     * @param witnessClass
     * @param classLoader for finding the witnessClass
     * @return true, if the given witnessClass exists, through the given classLoader.
     */
    public boolean exist(String witnessClass, ClassLoader classLoader) {
        ClassLoader mappingKey = classLoader == null ? NullClassLoader.INSTANCE : classLoader;
wu-sheng's avatar
wu-sheng 已提交
26
        if (!poolMap.containsKey(mappingKey)) {
27
            synchronized (poolMap) {
wu-sheng's avatar
wu-sheng 已提交
28
                if (!poolMap.containsKey(mappingKey)) {
29 30 31 32 33 34 35 36 37 38 39 40 41 42
                    TypePool classTypePool = classLoader == null ? TypePool.Default.ofClassPath() : TypePool.Default.of(classLoader);
                    poolMap.put(mappingKey, classTypePool);
                }
            }
        }
        TypePool typePool = poolMap.get(mappingKey);
        TypePool.Resolution witnessClassResolution = typePool.describe(witnessClass);
        return witnessClassResolution.isResolved();
    }
}

final class NullClassLoader extends ClassLoader {
    static NullClassLoader INSTANCE = new NullClassLoader();
}