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

rocks.bastion.core.view.Bindings Maven / Gradle / Ivy

package rocks.bastion.core.view;

import org.apache.commons.lang3.ClassUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * Represents a map of view bindings. Given a view type, will return the associated view with that binding.
 */
public final class Bindings {

    public static  Bindings single(Class viewType, T view) {
        Bindings bindings = new Bindings();
        bindings.addBinding(viewType, view);
        return bindings;
    }

    /**
     * Creates a Bindings object containing the entire class hierarchy of the given view type. All extended classes and interfaces
     * implemented by the given type will be bound to the specified view.
     *
     * @param viewType The class representing the type of view to bind
     * @param view The view object to bind
     * @param  The type of view to bind
     * @return A bindings object
     */
    @SuppressWarnings("unchecked")
    public static  Bindings hierarchy(Class viewType, T view) {
        Bindings bindings = new Bindings();
        for (Class superType : ClassUtils.hierarchy(viewType, ClassUtils.Interfaces.INCLUDE)) {
            bindings.addBinding((Class) superType, view);
        }
        return bindings;
    }

    private final Map, Object> bindings;

    public Bindings() {
        bindings = new HashMap<>();
    }

    public  void addBinding(Class viewType, T view) {
        Objects.requireNonNull(viewType);
        Objects.requireNonNull(view);
        bindings.put(viewType, view);
    }

    public void addAllBindings(Bindings bindings) {
        Objects.requireNonNull(bindings);
        this.bindings.putAll(bindings.bindings);
    }

    @SuppressWarnings("unchecked")
    public  Optional getViewForType(Class viewType) {
        return Optional.ofNullable((T) bindings.get(viewType));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy