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(obj, 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.canAccess(obj)) {
52        return field.get(obj);
53      }
54      return null;
55    }
56  
57    /**
58     * Pre.
59     *
60     * @param obj the obj
61     * @param field the field
62     *
63     * @return true, if successful
64     */
65    private boolean pre(Object obj, Field field) {
66      boolean accessible = field.canAccess(obj);
67      if (!accessible) {
68        try {
69          field.setAccessible(true);
70        } catch (SecurityException ex) {
71          logger.trace("", ex);
72        }
73      }
74      return accessible;
75    }
76  
77    /**
78     * Post.
79     *
80     * @param field the field
81     * @param value the value
82     */
83    private void post(Field field, boolean value) {
84      if (!value) {
85        try {
86          field.setAccessible(false);
87        } catch (SecurityException ex) {
88          logger.trace("", ex);
89        }
90      }
91    }
92  
93  }