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

com.spikeify.converters.SetConverter Maven / Gradle / Ivy

There is a newer version: 0.2.35
Show newest version
package com.spikeify.converters;

import com.spikeify.Converter;
import com.spikeify.NoArgClassConstructor;
import com.spikeify.SpikeifyError;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@SuppressWarnings("unchecked")
public class SetConverter implements Converter, List> {

	private final Class setType;
	private final Constructor noArgConstructor;

	public SetConverter(Class setType) {
		if (setType.equals(Set.class)) {
			setType = HashSet.class;
		}

		this.setType = setType;
		this.noArgConstructor = NoArgClassConstructor.getNoArgConstructor(setType);
	}

	public boolean canConvert(Class type) {
		return List.class.isAssignableFrom(type);
	}

	public Set fromProperty(List list) {
		if (list == null) {
			return null;
		}
		Set set;
		try {
			set = noArgConstructor.newInstance();
		} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
			throw new SpikeifyError("Error: could not instantiate '" + setType + "' via a default no-arg constructor.");
		}
		set.addAll(list);
		return set;
	}

	public List fromField(Set fieldValue) {
		return new ArrayList(fieldValue);
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy