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

com.maxifier.mxcache.impl.instanceprovider.BinderImpl Maven / Gradle / Ivy

/*
 * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved.
 */
package com.maxifier.mxcache.impl.instanceprovider;

import com.maxifier.mxcache.InstanceProvider;

import javax.annotation.Nonnull;

import java.util.Map;

/**
 * @author Alexander Kochurov ([email protected])
*/
class BinderImpl implements Binder {
    private final Class cls;
    private final InstanceProvider instanceProvider;
    private final Map registry;

    public BinderImpl(InstanceProvider instanceProvider, Map registry, Class cls) {
        this.instanceProvider = instanceProvider;
        this.registry = registry;
        this.cls = cls;
    }

    @Override
    public void toProvider(@Nonnull Provider provider) {
        registry.put(cls, provider);
    }

    @Override
    public void toInstance(@Nonnull T instance) {
        if (!cls.isInstance(instance)) {
            throw new IllegalArgumentException("Cannot bind " + cls + " to instance of " + instance.getClass());
        }
        registry.put(cls, new ConstProvider(instance));
    }

    @Override
    public void toClass(@Nonnull Class cls) {
        if (cls == this.cls) {
            throw new IllegalArgumentException("Cannot bind " + this.cls + " to itself");
        }
        if (!this.cls.isAssignableFrom(cls)) {
            throw new IllegalArgumentException("Cannot bind " + this.cls + " to " + cls);
        }
        registry.put(this.cls, new DelegatingProvider(instanceProvider, cls));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy