1
2
3
4
5
6
7
8
9
10
11 package psiprobe.tools;
12
13 import java.lang.reflect.Field;
14
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18
19
20
21 public class SimpleAccessor implements Accessor {
22
23
24 private static final Logger logger = LoggerFactory.getLogger(SimpleAccessor.class);
25
26 @Override
27 public Object get(Object obj, Field field) {
28 boolean accessible = pre(field);
29 try {
30 return get0(obj, field);
31 } catch (IllegalArgumentException | IllegalAccessException e) {
32 logger.trace("", e);
33 return null;
34 } finally {
35 post(field, accessible);
36 }
37 }
38
39
40
41
42
43
44
45
46
47
48
49 private Object get0(Object obj, Field field) throws IllegalAccessException {
50
51 if (field.isAccessible()) {
52 return field.get(obj);
53 }
54 return null;
55 }
56
57
58
59
60
61
62
63
64 private boolean pre(Field field) {
65 boolean accessible = field.isAccessible();
66 if (!accessible) {
67 try {
68 field.setAccessible(true);
69 } catch (SecurityException ex) {
70 logger.trace("", ex);
71 }
72 }
73 return accessible;
74 }
75
76
77
78
79
80
81
82 private void post(Field field, boolean value) {
83 if (!value) {
84 try {
85 field.setAccessible(false);
86 } catch (SecurityException ex) {
87 logger.trace("", ex);
88 }
89 }
90 }
91
92 }