01: /*
02: Copyright 2004-2007 Paul R. Holser, Jr. All rights reserved.
03: Licensed under the Academic Free License version 3.0
04: */
05:
06: package joptsimple;
07:
08: import java.lang.reflect.Constructor;
09: import java.lang.reflect.InvocationTargetException;
10: import java.lang.reflect.Member;
11: import java.lang.reflect.Method;
12: import java.lang.reflect.Modifier;
13:
14: /**
15: * Helper methods for reflection.
16: *
17: * @since 2.0
18: * @author <a href="mailto:pholser@alumni.rice.edu">Paul Holser</a>
19: * @version $Id: Reflection.java,v 1.15 2007/04/10 20:06:25 pholser Exp $
20: */
21: class Reflection {
22: protected Reflection() {
23: throw new UnsupportedOperationException();
24: }
25:
26: static Member findConverter(Class clazz) {
27: Member method = findConverterMethod(clazz);
28: if (method != null)
29: return method;
30:
31: Member constructor = findConverterConstructor(clazz);
32: if (constructor != null)
33: return constructor;
34:
35: throw new IllegalArgumentException(clazz
36: + " is not a value type");
37: }
38:
39: private static Method findConverterMethod(Class aClass) {
40: try {
41: Method valueOf = aClass.getDeclaredMethod("valueOf",
42: new Class[] { String.class });
43:
44: return matchesConverterRequirements(valueOf, aClass) ? valueOf
45: : null;
46: } catch (NoSuchMethodException ignored) {
47: return null;
48: }
49: }
50:
51: private static boolean matchesConverterRequirements(Method method,
52: Class expectedReturnType) {
53:
54: int modifiers = method.getModifiers();
55: return Modifier.isPublic(modifiers)
56: && Modifier.isStatic(modifiers)
57: && expectedReturnType.equals(method.getReturnType());
58: }
59:
60: private static Constructor findConverterConstructor(Class clazz) {
61: try {
62: return clazz.getConstructor(new Class[] { String.class });
63: } catch (NoSuchMethodException ignored) {
64: return null;
65: }
66: }
67:
68: static Object invokeQuietly(Constructor constructor, Object[] args) {
69: try {
70: return constructor.newInstance(args);
71: } catch (InstantiationException ex) {
72: throw new ReflectionException(ex);
73: } catch (IllegalAccessException ex) {
74: throw new ReflectionException(ex);
75: } catch (InvocationTargetException ex) {
76: throw new ReflectionException(ex);
77: } catch (IllegalArgumentException ex) {
78: throw new ReflectionException(ex);
79: }
80: }
81:
82: static Object invokeQuietly(Method method, Object[] args) {
83: try {
84: return method.invoke(null, args);
85: } catch (IllegalAccessException ex) {
86: throw new ReflectionException(ex);
87: } catch (InvocationTargetException ex) {
88: throw new ReflectionException(ex.getTargetException());
89: } catch (IllegalArgumentException ex) {
90: throw new ReflectionException(ex);
91: }
92: }
93: }
|