fork download
  1. import java.lang.reflect.InvocationTargetException;
  2. import java.lang.reflect.Method;
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Collection;
  6. import java.util.List;
  7.  
  8. public class Main
  9. {
  10. static <A,B> void addAll(Collection<B> dest, Collection<A> source, String methodName)
  11. {
  12. Method m = null;
  13. for (A a: source)
  14. {
  15. if (m == null)
  16. m = a.getClass().getMethod(methodName);
  17. dest.add((B)m.invoke(a));
  18. }
  19. }
  20.  
  21. public static void main(String[] args) throws Exception
  22. {
  23. ArrayList<String> s = new ArrayList<String>();
  24. List<Integer> i = Arrays.asList(1,2,3);
  25. addAll(s, i, "toString");
  26. System.out.println(s);
  27. }
  28. }
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
[1, 2, 3]