Last active
August 29, 2015 14:11
-
-
Save noherczeg/ce72e5d204b78507e95f to your computer and use it in GitHub Desktop.
Prototype generic transformer parent class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hu.noherczeg.guildwatch.core; | |
import java.lang.reflect.ParameterizedType; | |
import java.util.LinkedList; | |
import java.util.List; | |
/** | |
* The source(es) parameter in all the methods should always be final, to ensure that it's values don't change | |
* while the iterations are in progress! | |
* | |
* S -> T | |
* | |
* @param <S> | |
* @param <T> | |
*/ | |
public abstract class AbstractTransformer<S, T> { | |
/** | |
* Transforms the source into a new instance of the target Type. | |
* | |
* @param source Source instance | |
* @return New instance of Target Type | |
*/ | |
@SuppressWarnings("unchecked") | |
public T transform (S source) { | |
T freshTarget = null; | |
try { | |
// Sorcery :O | |
freshTarget = ((Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]).newInstance(); | |
} catch (InstantiationException | IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
mold(source, freshTarget); | |
return freshTarget; | |
} | |
/** | |
* Molds the source instance's fields into the target instance | |
* | |
* @param source Source instance | |
* @param target Target instance | |
*/ | |
public abstract void mold (S source, T target); | |
/** | |
* Transforms a Collection of source elements to a List of elements of the given type. | |
* The internal implementation is a LinkedList just to ensure the order of the results, | |
* in case the parameter is of the given type. | |
* | |
* @param sources Collection of sources | |
* @return Order safe list of elements of the given type | |
*/ | |
public List<T> transform (Iterable<S> sources) { | |
List<T> results = new LinkedList<>(); | |
for (S source: sources) { | |
results.add(transform(source)); | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment