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

net.entropysoft.transmorph.converters.collections.CollectionToString Maven / Gradle / Ivy

Go to download

Java library to convert a Java object of one type into an object of another type (with another signature, possibly parameterized).

There is a newer version: 3.1.3
Show newest version
package net.entropysoft.transmorph.converters.collections;

import java.util.Collection;

import net.entropysoft.transmorph.ConversionContext;
import net.entropysoft.transmorph.ConverterException;
import net.entropysoft.transmorph.converters.AbstractContainerConverter;
import net.entropysoft.transmorph.type.TypeReference;

public class CollectionToString extends AbstractContainerConverter {

	private IStringArrayFormatter stringArrayFormatter = new DefaultStringArrayFormatter();	
	
	public CollectionToString() {
		this.useObjectPool = false;
	}	
	
	public IStringArrayFormatter getStringArrayFormatter() {
		return stringArrayFormatter;
	}

	public void setStringArrayFormatter(IStringArrayFormatter stringArrayFormatter) {
		this.stringArrayFormatter = stringArrayFormatter;
	}

	public Object doConvert(ConversionContext context, Object sourceObject, TypeReference destinationType) throws ConverterException {
		if (sourceObject == null) {
			return null;
		}

		Collection collection = (Collection) sourceObject;

		String[] stringArray = new String[collection.size()];
		
		int i = 0;
		for (Object element : collection) {
			String elementConverted = (String)elementConverter.convert(
					context, element, destinationType);
			stringArray[i] = elementConverted;
			i++;
		}

		return stringArrayFormatter.format(stringArray);
	}

	protected boolean canHandleDestinationType(TypeReference destinationType) {
		return destinationType.isType(String.class);
	}

	protected boolean canHandleSourceObject(Object sourceObject) {
		if (sourceObject == null) {
			return true;
		}
		return sourceObject instanceof Collection;
	}

}