View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  
18  package org.apache.logging.log4j.core.util;
19  
20  import java.lang.reflect.AccessibleObject;
21  import java.lang.reflect.Constructor;
22  import java.lang.reflect.Field;
23  import java.lang.reflect.InvocationTargetException;
24  import java.lang.reflect.Member;
25  import java.lang.reflect.Modifier;
26  import java.util.Objects;
27  
28  /**
29   * Utility class for performing common reflective operations.
30   *
31   * @since 2.1
32   */
33  public final class ReflectionUtil {
34      private ReflectionUtil() {
35      }
36  
37      /**
38       * Indicates whether or not a {@link Member} is both public and is contained in a public class.
39       *
40       * @param <T> type of the object whose accessibility to test
41       * @param member the Member to check for public accessibility (must not be {@code null}).
42       * @return {@code true} if {@code member} is public and contained in a public class.
43       * @throws NullPointerException if {@code member} is {@code null}.
44       */
45      public static <T extends AccessibleObject & Member> boolean isAccessible(final T member) {
46          Objects.requireNonNull(member, "No member provided");
47          return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers());
48      }
49  
50      /**
51       * Makes a {@link Member} {@link AccessibleObject#isAccessible() accessible} if the member is not public.
52       *
53       * @param <T> type of the object to make accessible
54       * @param member the Member to make accessible (must not be {@code null}).
55       * @throws NullPointerException if {@code member} is {@code null}.
56       */
57      public static <T extends AccessibleObject & Member> void makeAccessible(final T member) {
58          if (!isAccessible(member) && !member.isAccessible()) {
59              member.setAccessible(true);
60          }
61      }
62  
63      /**
64       * Makes a {@link Field} {@link AccessibleObject#isAccessible() accessible} if it is not public or if it is final.
65       *
66       * <p>Note that using this method to make a {@code final} field writable will most likely not work very well due to
67       * compiler optimizations and the like.</p>
68       *
69       * @param field the Field to make accessible (must not be {@code null}).
70       * @throws NullPointerException if {@code field} is {@code null}.
71       */
72      public static void makeAccessible(final Field field) {
73          Objects.requireNonNull(field, "No field provided");
74          if ((!isAccessible(field) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
75              field.setAccessible(true);
76          }
77      }
78  
79      /**
80       * Gets the value of a {@link Field}, making it accessible if required.
81       *
82       * @param field    the Field to obtain a value from (must not be {@code null}).
83       * @param instance the instance to obtain the field value from or {@code null} only if the field is static.
84       * @return the value stored by the field.
85       * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
86       *                              {@code field} is not {@code static}.
87       * @see Field#get(Object)
88       */
89      public static Object getFieldValue(final Field field, final Object instance) {
90          makeAccessible(field);
91          if (!Modifier.isStatic(field.getModifiers())) {
92              Objects.requireNonNull(instance, "No instance given for non-static field");
93          }
94          try {
95              return field.get(instance);
96          } catch (final IllegalAccessException e) {
97              throw new UnsupportedOperationException(e);
98          }
99      }
100 
101     /**
102      * Gets the value of a static {@link Field}, making it accessible if required.
103      *
104      * @param field the Field to obtain a value from (must not be {@code null}).
105      * @return the value stored by the static field.
106      * @throws NullPointerException if {@code field} is {@code null}, or if {@code field} is not {@code static}.
107      * @see Field#get(Object)
108      */
109     public static Object getStaticFieldValue(final Field field) {
110         return getFieldValue(field, null);
111     }
112 
113     /**
114      * Sets the value of a {@link Field}, making it accessible if required.
115      *
116      * @param field    the Field to write a value to (must not be {@code null}).
117      * @param instance the instance to write the value to or {@code null} only if the field is static.
118      * @param value    the (possibly wrapped) value to write to the field.
119      * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
120      *                              {@code field} is not {@code static}.
121      * @see Field#set(Object, Object)
122      */
123     public static void setFieldValue(final Field field, final Object instance, final Object value) {
124         makeAccessible(field);
125         if (!Modifier.isStatic(field.getModifiers())) {
126             Objects.requireNonNull(instance, "No instance given for non-static field");
127         }
128         try {
129             field.set(instance, value);
130         } catch (final IllegalAccessException e) {
131             throw new UnsupportedOperationException(e);
132         }
133     }
134 
135     /**
136      * Sets the value of a static {@link Field}, making it accessible if required.
137      *
138      * @param field the Field to write a value to (must not be {@code null}).
139      * @param value the (possibly wrapped) value to write to the field.
140      * @throws NullPointerException if {@code field} is {@code null}, or if {@code field} is not {@code static}.
141      * @see Field#set(Object, Object)
142      */
143     public static void setStaticFieldValue(final Field field, final Object value) {
144         setFieldValue(field, null, value);
145     }
146 
147     /**
148      * Gets the default (no-arg) constructor for a given class.
149      *
150      * @param clazz the class to find a constructor for
151      * @param <T>   the type made by the constructor
152      * @return the default constructor for the given class
153      * @throws IllegalStateException if no default constructor can be found
154      */
155     public static <T> Constructor<T> getDefaultConstructor(final Class<T> clazz) {
156         Objects.requireNonNull(clazz, "No class provided");
157         try {
158             final Constructor<T> constructor = clazz.getDeclaredConstructor();
159             makeAccessible(constructor);
160             return constructor;
161         } catch (final NoSuchMethodException ignored) {
162             try {
163                 final Constructor<T> constructor = clazz.getConstructor();
164                 makeAccessible(constructor);
165                 return constructor;
166             } catch (final NoSuchMethodException e) {
167                 throw new IllegalStateException(e);
168             }
169         }
170     }
171 
172     /**
173      * Constructs a new {@code T} object using the default constructor of its class. Any exceptions thrown by the
174      * constructor will be rethrown by this method, possibly wrapped in an
175      * {@link java.lang.reflect.UndeclaredThrowableException}.
176      *
177      * @param clazz the class to use for instantiation.
178      * @param <T>   the type of the object to construct.
179      * @return a new instance of T made from its default constructor.
180      * @throws IllegalArgumentException if the given class is abstract, an interface, an array class, a primitive type,
181      *                                  or void
182      * @throws IllegalStateException    if access is denied to the constructor, or there are no default constructors
183      */
184     public static <T> T instantiate(final Class<T> clazz) {
185         Objects.requireNonNull(clazz, "No class provided");
186         final Constructor<T> constructor = getDefaultConstructor(clazz);
187         try {
188             return constructor.newInstance();
189         } catch (final NoClassDefFoundError | InstantiationException e) {
190             // LOG4J2-1051
191             // On platforms like Google App Engine and Android, some JRE classes are not supported: JMX, JNDI, etc.
192             throw new IllegalArgumentException(e);
193         } catch (final IllegalAccessException e) {
194             throw new IllegalStateException(e);
195         } catch (final InvocationTargetException e) {
196             Throwables.rethrow(e.getCause());
197             throw new InternalError("Unreachable");
198         }
199     }
200 }