summaryrefslogtreecommitdiff
path: root/src/main/java/com/beust/jcommander/Parameterized.java
blob: 32640083dfa6817ebeb00b4e4c08e60d1c0f4a0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package com.beust.jcommander;

import com.beust.jcommander.internal.Lists;
import com.beust.jcommander.internal.Sets;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * Encapsulate a field or a method annotated with @Parameter or @DynamicParameter
 */
public class Parameterized {

  // Either a method or a field
  private Field field;
  private Method method;
  private Method getter;

  // Either of these two
  private WrappedParameter wrappedParameter;
  private ParametersDelegate parametersDelegate;

  public Parameterized(WrappedParameter wp, ParametersDelegate pd,
      Field field, Method method) {
    wrappedParameter = wp;
    this.method = method;
    this.field = field;
    if (this.field != null) {
      setFieldAccessible(this.field);
    }
    parametersDelegate = pd;
  }

  /**
   * Recursive handler for describing the set of classes while
   * using the setOfClasses parameter as a collector
   *
   * @param inputClass the class to analyze
   * @param setOfClasses the set collector to collect the results
     */
  private static void describeClassTree(Class<?> inputClass, Set<Class<?>> setOfClasses) {
    // can't map null class
    if(inputClass == null) {
      return;
    }

    // don't further analyze a class that has been analyzed already
    if(Object.class.equals(inputClass) || setOfClasses.contains(inputClass)) {
      return;
    }

    // add to analysis set
    setOfClasses.add(inputClass);

    // perform super class analysis
    describeClassTree(inputClass.getSuperclass(), setOfClasses);

    // perform analysis on interfaces
    for(Class<?> hasInterface : inputClass.getInterfaces()) {
      describeClassTree(hasInterface, setOfClasses);
    }
  }

  /**
   * Given an object return the set of classes that it extends
   * or implements.
   *
   * @param arg object to describe
   * @return set of classes that are implemented or extended by that object
   */
  private static Set<Class<?>> describeClassTree(Class<?> inputClass) {
    if(inputClass == null) {
      return Collections.emptySet();
    }

    // create result collector
    Set<Class<?>> classes = Sets.newLinkedHashSet();

    // describe tree
    describeClassTree(inputClass, classes);

    return classes;
  }

  public static List<Parameterized> parseArg(Object arg) {
    List<Parameterized> result = Lists.newArrayList();

    Class<?> rootClass = arg.getClass();

    // get the list of types that are extended or implemented by the root class
    // and all of its parent types
    Set<Class<?>> types = describeClassTree(rootClass);

    // analyze each type
    for(Class<?> cls : types) {

      // check fields
      for (Field f : cls.getDeclaredFields()) {
        Annotation annotation = f.getAnnotation(Parameter.class);
        Annotation delegateAnnotation = f.getAnnotation(ParametersDelegate.class);
        Annotation dynamicParameter = f.getAnnotation(DynamicParameter.class);
        if (annotation != null) {
          result.add(new Parameterized(new WrappedParameter((Parameter) annotation), null,
                  f, null));
        } else if (dynamicParameter != null) {
          result.add(new Parameterized(new WrappedParameter((DynamicParameter) dynamicParameter), null,
                  f, null));
        } else if (delegateAnnotation != null) {
          result.add(new Parameterized(null, (ParametersDelegate) delegateAnnotation,
                  f, null));
        }
      }

      // check methods
      for (Method m : cls.getDeclaredMethods()) {
        m.setAccessible(true);
        Annotation annotation = m.getAnnotation(Parameter.class);
        Annotation delegateAnnotation = m.getAnnotation(ParametersDelegate.class);
        Annotation dynamicParameter = m.getAnnotation(DynamicParameter.class);
        if (annotation != null) {
          result.add(new Parameterized(new WrappedParameter((Parameter) annotation), null,
                  null, m));
        } else if (dynamicParameter != null) {
          result.add(new Parameterized(new WrappedParameter((DynamicParameter) dynamicParameter), null,
                  null, m));
        } else if (delegateAnnotation != null) {
          result.add(new Parameterized(null, (ParametersDelegate) delegateAnnotation,
                  null, m));
        }
      }
    }

    return result;
  }

  public WrappedParameter getWrappedParameter() {
    return wrappedParameter;
  }

  public Class<?> getType() {
    if (method != null) {
      return method.getParameterTypes()[0];
    } else {
      return field.getType();
    }
  }

  public String getName() {
    if (method != null) {
      return method.getName();
    } else {
      return field.getName();
    }
  }

  public Object get(Object object) {
    try {
      if (method != null) {
        if (getter == null) {
            getter = method.getDeclaringClass()
                .getMethod("g" + method.getName().substring(1));
        }
        return getter.invoke(object);
      } else {
        return field.get(object);
      }
    } catch (SecurityException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
      throw new ParameterException(e);
    } catch (NoSuchMethodException e) {
      // Try to find a field
      String name = method.getName();
      String fieldName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
      Object result = null;
      try {
        Field field = method.getDeclaringClass().getDeclaredField(fieldName);
        if (field != null) {
          setFieldAccessible(field);
          result = field.get(object);
        }
      } catch(NoSuchFieldException | IllegalAccessException ex) {
        // ignore
      }
      return result;
    }
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((field == null) ? 0 : field.hashCode());
    result = prime * result + ((method == null) ? 0 : method.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Parameterized other = (Parameterized) obj;
    if (field == null) {
      if (other.field != null)
        return false;
    } else if (!field.equals(other.field))
      return false;
    if (method == null) {
      if (other.method != null)
        return false;
    } else if (!method.equals(other.method))
      return false;
    return true;
  }

  public boolean isDynamicParameter(Field field) {
    if (method != null) {
      return method.getAnnotation(DynamicParameter.class) != null;
    } else {
      return this.field.getAnnotation(DynamicParameter.class) != null;
    }
  }

  private static void setFieldAccessible(Field f) {
    if (Modifier.isFinal(f.getModifiers())) {
      throw new ParameterException(
        "Cannot use final field " + f.getDeclaringClass().getName() + "#" + f.getName() + " as a parameter;"
        + " compile-time constant inlining may hide new values written to it.");
    }
    f.setAccessible(true);
  }

  private static String errorMessage(Method m, Exception ex) {
    return "Could not invoke " + m + "\n    Reason: " + ex.getMessage();
  }

  public void set(Object object, Object value) {
    try {
      if (method != null) {
        method.invoke(object, value);
      } else {
          field.set(object, value);
      }
    } catch (IllegalAccessException | IllegalArgumentException ex) {
      throw new ParameterException(errorMessage(method, ex));
    } catch (InvocationTargetException ex) {
      // If a ParameterException was thrown, don't wrap it into another one
      if (ex.getTargetException() instanceof ParameterException) {
        throw (ParameterException) ex.getTargetException();
      } else {
        throw new ParameterException(errorMessage(method, ex));
      }
    }
  }

  public ParametersDelegate getDelegateAnnotation() {
    return parametersDelegate;
  }

  public Type getGenericType() {
    if (method != null) {
      return method.getGenericParameterTypes()[0];
    } else {
      return field.getGenericType();
    }
  }

  public Parameter getParameter() {
    return wrappedParameter.getParameter();
  }

  /**
   * @return the generic type of the collection for this field, or null if not applicable.
   */
  public Type findFieldGenericType() {
    if (method != null) {
      return null;
    } else {
      if (field.getGenericType() instanceof ParameterizedType) {
        ParameterizedType p = (ParameterizedType) field.getGenericType();
        Type cls = p.getActualTypeArguments()[0];
        if (cls instanceof Class) {
          return cls;
        }
      }
    }

    return null;
  }

  public boolean isDynamicParameter() {
    return wrappedParameter.getDynamicParameter() != null;
  }

}