forked from ToToTec/CmdOption
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBooleanOptionHandler.java
56 lines (51 loc) · 1.61 KB
/
BooleanOptionHandler.java
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
package de.tototec.cmdoption.handler;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Apply an zero-arg option to an {@link Boolean} (or <code>boolean</code>)
* field. If the option is present, the field will be evaluated to
* <code>true</code>.
*
*/
public class BooleanOptionHandler implements CmdOptionHandler {
public void applyParams(final Object config, final AccessibleObject element, final String[] args,
final String optionName) {
try {
if (element instanceof Field) {
final Field field = (Field) element;
field.set(config, true);
} else {
final Method method = (Method) element;
if (method.getParameterTypes().length == 1) {
method.invoke(config, true);
} else {
method.invoke(config);
}
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
public boolean canHandle(final AccessibleObject element, final int argCount) {
if (argCount != 0)
return false;
if (element instanceof Field) {
final Field field = (Field) element;
final Class<?> type = field.getType();
return !Modifier.isFinal(field.getModifiers())
&& (boolean.class.equals(type) || Boolean.class.equals(type));
} else if (element instanceof Method) {
final Method method = (Method) element;
if (method.getParameterTypes().length == 0) {
return true;
}
if (method.getParameterTypes().length == 1) {
final Class<?> type = method.getParameterTypes()[0];
return boolean.class.equals(type) || Boolean.class.equals(type);
}
}
return false;
}
}