View Javadoc

1   package org.kohsuke.args4j;
2   
3   import org.kohsuke.args4j.spi.Setter;
4   
5   import java.lang.reflect.InvocationTargetException;
6   import java.lang.reflect.Method;
7   
8   /***
9    * {@link Setter} that sets to a {@link Method}.
10   *
11   * @author Kohsuke Kawaguchi
12   */
13  final class MethodSetter implements Setter {
14      private final Object bean;
15      private final Method m;
16  
17      public MethodSetter(Object bean, Method m) {
18          this.bean = bean;
19          this.m = m;
20          if(m.getParameterTypes().length!=1)
21              throw new IllegalAnnotationError(Messages.ILLEGAL_METHOD_SIGNATURE.format(m));
22      }
23  
24      public Class getType() {
25          return m.getParameterTypes()[0];
26      }
27  
28      public void addValue(Object value) throws CmdLineException {
29          try {
30              try {
31                  m.invoke(bean,value);
32              } catch (IllegalAccessException _) {
33                  // try again
34                  m.setAccessible(true);
35                  try {
36                      m.invoke(bean,value);
37                  } catch (IllegalAccessException e) {
38                      throw new IllegalAccessError(e.getMessage());
39                  }
40              }
41          } catch (InvocationTargetException e) {
42              Throwable t = e.getTargetException();
43              if(t instanceof RuntimeException)
44                  throw (RuntimeException)t;
45              if(t instanceof Error)
46                  throw (Error)t;
47              if(t instanceof CmdLineException)
48                  throw (CmdLineException)t;
49  
50              // otherwise wrap
51              if(t!=null)
52                  throw new CmdLineException(t);
53              else
54                  throw new CmdLineException(e);
55          }
56      }
57  }