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

trip.spi.helpers.ManyElementsProvidableField Maven / Gradle / Ivy

package trip.spi.helpers;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Collection;

import lombok.RequiredArgsConstructor;
import lombok.val;
import trip.spi.ProvidedServices;
import trip.spi.ServiceProvider;
import trip.spi.ServiceProviderException;
import trip.spi.helpers.filter.Condition;
import trip.spi.helpers.filter.QualifierCondition;

@RequiredArgsConstructor
@SuppressWarnings( { "unchecked" } )
public class ManyElementsProvidableField implements ProvidableField {

	final Field field;
	final Class fieldType;
	final Condition condition;

	@Override
	public void provide( final Object instance, final ServiceProvider provider )
		throws ServiceProviderException, IllegalArgumentException, IllegalAccessException {
		final Object value = provider.loadAll( fieldType, condition );
		set( instance, value );
	}

	public void set( final Object instance, final Object value ) throws IllegalArgumentException, IllegalAccessException {
		field.set( instance, value );
	}

	public static  ProvidableField from( Collection> qualifiers, final Field field ) {
		assertFieldTypeIsIterable( field );
		field.setAccessible( true );
		val provided = field.getAnnotation( ProvidedServices.class );
		return new ManyElementsProvidableField(
			field, (Class)provided.exposedAs(),
			(Condition)new QualifierCondition<>(qualifiers) );
	}

	private static void assertFieldTypeIsIterable( final Field field ) {
		if ( !Iterable.class.equals( field.getType() ) )
			throw new IllegalStateException( "Field " + field.getName() + " expects to have Iterable type." );
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy