Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 17th, 2012  |  syntax: None  |  size: 1.06 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Java reflection when a method has a variable arglist
  2. public class A {
  3.     public void theMethod(Object arg1) {
  4.         // do some stuff with a single argument
  5.     }
  6. }
  7.  
  8. public class B {
  9.     public void reflectingMethod(Object arg) {
  10.         Method method = A.class.getMethod("theMethod", Object.class);
  11.         method.invoke(new A(), arg);
  12.     }
  13. }
  14.        
  15. public class A {
  16.     public void theMethod(Object... args) {
  17.         // do some stuff with a list of arguments
  18.     }
  19. }
  20.  
  21. public class B {
  22.     public void reflectingMethod(Object... args) {
  23.         Method method = A.class.getMethod("theMethod", /* what goes here ? */);
  24.         method.invoke(new A(), args);
  25.     }
  26. }
  27.        
  28. A.class.getMethod("theMethod", Object[].class);
  29.        
  30. public class A {
  31.     public void theMethod(ArrayList<Object> args) { // do stuff
  32.     }
  33. }
  34.  
  35. public class B {
  36.     public void reflectingMethod(ArrayList<Object> args) {
  37.         Method method;
  38.         try {
  39.             method = A.class.getMethod("theMethod", args.getClass());
  40.             method.invoke(new A(), args);
  41.         } catch (Exception e) {}
  42.     }
  43. }