View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
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   * The Class SimpleAccessor.
20   */
21  public class SimpleAccessor implements Accessor {
22  
23    /** The Constant logger. */
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     * Gets the 0.
41     *
42     * @param obj the obj
43     * @param field the field
44     *
45     * @return the 0
46     *
47     * @throws IllegalAccessException the illegal access exception
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     * Pre.
59     *
60     * @param field the field
61     *
62     * @return true, if successful
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     * Post.
78     *
79     * @param field the field
80     * @param value the value
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  }