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

org.rx.core.IOC Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.core;

import lombok.NonNull;
import lombok.SneakyThrows;
import org.apache.commons.lang3.ClassUtils;
import org.rx.bean.WeakIdentityMap;
import org.rx.exception.InvalidException;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;

import static org.rx.core.Constants.NON_UNCHECKED;

@SuppressWarnings(NON_UNCHECKED)
public final class IOC {
    static final Map, Object> container = new ConcurrentHashMap<>(8);
    static final Map WEAK_MAP = Collections.synchronizedMap(new WeakHashMap<>());
    //不要放值类型
    static final Map WEAK_IDENTITY_MAP = new WeakIdentityMap<>();

    public static  boolean isInit(Class type) {
        return container.containsKey(type);
    }

    public static  T get(Class type, Class defType) {
        T bean = innerGet(type);
        if (bean == null) {
            return get(defType);
        }
        return bean;
    }

    public static  T get(Class type) {
        T bean = innerGet(type);
        if (bean == null) {
            throw new InvalidException("Bean {} not registered", type.getName());
        }
        return bean;
    }

    @SneakyThrows
    static synchronized  T innerGet(Class type) {
        T bean = (T) container.get(type);
        if (bean == null) {
            Class.forName(type.getName());
            bean = (T) container.get(type);
        }
        return bean;
    }

    public static  void register(@NonNull Class type, @NonNull T bean) {
        List> types = ClassUtils.getAllSuperclasses(type);
        types.remove(Object.class);
        for (Class t : types) {
            container.putIfAbsent(t, bean);
        }
        container.put(type, bean);
    }

    public static  void unregister(Class type) {
        container.remove(type);
    }

    public static  Map weakMap(boolean identity) {
        return identity ? WEAK_IDENTITY_MAP : WEAK_MAP;
    }

    static  Map weakMap(Object ref, boolean identity) {
        return (Map) (identity ? WEAK_IDENTITY_MAP : WEAK_MAP).computeIfAbsent(ref, k -> new ConcurrentHashMap<>(4));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy