Skip to content

Instantly share code, notes, and snippets.

@ledsun
Forked from nagise/GenericListConverterSample
Created January 13, 2012 06:00
Show Gist options
  • Save ledsun/1604855 to your computer and use it in GitHub Desktop.
Save ledsun/1604855 to your computer and use it in GitHub Desktop.
ジェネリックなListの詰替えサンプル(引数で変換先の型を取ればいける)
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
public class Converter {
public static <T, U> List<U> convert(List<T> in, Class<U> type) {
List<U> out = new ArrayList<U>();
try {
for (T t : in) {
U u = type.newInstance();
BeanUtils.copyProperties(u, t);
out.add(u);
}
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
} catch (InvocationTargetException e) {
throw new IllegalArgumentException(e);
}
return out;
}
}
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class ConverterTest {
@Test
public void リストの詰め替え() {
List<A> source = new ArrayList<A>();
source.add(new A());
List<B> ret = Converter.convert(source, B.class);
assertThat(ret.get(0).val, is("a"));
}
public static class A {
private String val = "a";
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
}
public static class B {
private String val;
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment