-
-
Save ledsun/1604855 to your computer and use it in GitHub Desktop.
ジェネリックなListの詰替えサンプル(引数で変換先の型を取ればいける)
This file contains hidden or 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
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; | |
} | |
} |
This file contains hidden or 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
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