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

se.jbee.inject.config.Presets Maven / Gradle / Ivy

There is a newer version: 0.6
Show newest version
/*
 *  Copyright (c) 2012, Jan Bernitt 
 *			
 *  Licensed under the Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
 */
package se.jbee.inject.config;

import java.util.IdentityHashMap;

import se.jbee.inject.Type;

/**
 * {@link Presets} are an immutable associative data structure associating a exact {@link Type}
 * (including generics) with a value for/of that exact given type. These values act as input
 * parameters to the bootstrapping process. The values are used within modules that depend on
 * data that is given as program input.
 * 
 * @author Jan Bernitt ([email protected])
 */
public final class Presets {

	public static final Presets EMPTY = new Presets( new IdentityHashMap( 0 ) );

	private final IdentityHashMap values;

	private Presets( IdentityHashMap values ) {
		super();
		this.values = values;
	}

	/**
	 * @see #preset(Type, Object)
	 */
	public  Presets preset( Class type, T value ) {
		return preset( Type.raw( type ), value );
	}

	/**
	 * @return new {@link Presets} instance with the given key-value association. Any existing
	 *         association of the same key will be overridden.
	 */
	public  Presets preset( Type type, T value ) {
		final String key = key( type );
		if ( value == null && !values.containsKey( key ) ) {
			return this;
		}
		@SuppressWarnings ( "unchecked" )
		IdentityHashMap clone = (IdentityHashMap) values.clone();
		if ( value == null ) {
			clone.remove( key );
		} else {
			clone.put( key, value );
		}
		return new Presets( clone );
	}

	/**
	 * @return The value associated with the given exact {@link Type} or null of no
	 *         value is associated with it.
	 */
	@SuppressWarnings ( "unchecked" )
	public  T value( Type type ) {
		return (T) values.get( key( type ) );
	}

	private static  String key( Type type ) {
		return type.toString().intern();
	}

	@Override
	public String toString() {
		return values.toString();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy