Skip to content

Instantly share code, notes, and snippets.

@FGtatsuro
Forked from nagise/GenericListConverterSample
Created January 13, 2012 16:34
Show Gist options
  • Save FGtatsuro/1607375 to your computer and use it in GitHub Desktop.
Save FGtatsuro/1607375 to your computer and use it in GitHub Desktop.
ジェネリックなListの詰替えサンプル
public static <T,U> List<U> hoge(List<T> in) {
class InstanceGenerator<X> {
X instance(X ... x) throws InstantiationException, IllegalAccessException {
Class<?> xArrayClass = x.getClass();
Class<X> xClass = (Class<X>) xArrayClass.getComponentType();
return xClass.newInstance();
}
}
InstanceGenerator<U> d = new InstanceGenerator<U>();
List<U> out = new ArrayList<U>();
try {
for (T t : in) {
U u = d.instance();
// TODO t->u
out.add(u);
}
} catch (InstantiationException e) {
throw new IllegalArgumentException(e);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment