All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jianggujin.http.support.JApiStore Maven / Gradle / Ivy

The newest version!
/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.http.support;

import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.jianggujin.http.core.JHttpException;

/**
 * API仓库
 * 
 * @author jianggujin
 *
 */
public class JApiStore {
    private static Map, Object> apiCache = new ConcurrentHashMap, Object>();

    /**
     * 获得API
     * 
     * @param clazz
     * @return
     * @throws JHttpException
     */
    @SuppressWarnings("unchecked")
    public static  T getApi(Class clazz) throws JHttpException {
        if (clazz == null) {
            throw new IllegalArgumentException("clazz must not be null");
        }
        Object obj = apiCache.get(clazz);
        if (obj == null) {
            synchronized (clazz) {
                obj = apiCache.get(clazz);
                if (obj == null) {
                    try {
                        obj = (T) Proxy.newProxyInstance(clazz.getClassLoader(),
                                clazz.isInterface() ? new Class[] { clazz } : clazz.getInterfaces(),
                                new JApiInvocationHandler(clazz));
                        apiCache.put(clazz, obj);
                    } catch (Exception e) {
                        throw new JHttpException(e);
                    }
                }
            }
        }
        return (T) obj;
    }

    /**
     * 移除缓存
     * 
     * @param clazz
     */
    public static void remove(Class clazz) {
        if (clazz == null) {
            return;
        }
        synchronized (clazz) {
            apiCache.remove(clazz);
        }
    }

    /**
     * 清空
     */
    public static void clear() {
        apiCache.clear();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy