Skip to content

Instantly share code, notes, and snippets.

@nagise
Created January 13, 2012 03:53
Show Gist options
  • Save nagise/1604601 to your computer and use it in GitHub Desktop.
Save nagise/1604601 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