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 member the Member to check for public accessibility (must not be {@code null}).
41       * @return {@code true} if {@code member} is public and contained in a public class.
42       * @throws NullPointerException if {@code member} is {@code null}.
43       */
44      public static <T extends AccessibleObject & Member> boolean isAccessible(final T member) {
45          Objects.requireNonNull(member, "No member provided");
46          return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers());
47      }
48  
49      /**
50       * Makes a {@link Member} {@link AccessibleObject#isAccessible() accessible} if the member is not public.
51       *
52       * @param member the Member to make accessible (must not be {@code null}).
53       * @throws NullPointerException if {@code member} is {@code null}.
54       */
55      public static <T extends AccessibleObject & Member> void makeAccessible(final T member) {
56          if (!isAccessible(member) && !member.isAccessible()) {
57              member.setAccessible(true);
58          }
59      }
60  
61      /**
62       * Makes a {@link Field} {@link AccessibleObject#isAccessible() accessible} if it is not public or if it is final.
63       *
64       * <p>Note that using this method to make a {@code final} field writable will most likely not work very well due to
65       * compiler optimizations and the like.</p>
66       *
67       * @param field the Field to make accessible (must not be {@code null}).
68       * @throws NullPointerException if {@code field} is {@code null}.
69       */
70      public static void makeAccessible(final Field field) {
71          Objects.requireNonNull(field, "No field provided");
72          if ((!isAccessible(field) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
73              field.setAccessible(true);
74          }
75      }
76  
77      /**
78       * Gets the value of a {@link Field}, making it accessible if required.
79       *
80       * @param field    the Field to obtain a value from (must not be {@code null}).
81       * @param instance the instance to obtain the field value from or {@code null} only if the field is static.
82       * @return the value stored by the field.
83       * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
84       *                              {@code field} is not {@code static}.
85       * @see Field#get(Object)
86       */
87      public static Object getFieldValue(final Field field, final Object instance) {
88          makeAccessible(field);
89          if (!Modifier.isStatic(field.getModifiers())) {
90              Objects.requireNonNull(instance, "No instance given for non-static field");
91          }
92          try {
93              return field.get(instance);
94          } catch (final IllegalAccessException e) {
95              throw new UnsupportedOperationException(e);
96          }
97      }
98  
99      /**
100      * Gets the value of a static {@link Field}, making it accessible if required.
101      *
102      * @param field the Field to obtain a value from (must not be {@code null}).
103      * @return the value stored by the static field.
104      * @throws NullPointerException if {@code field} is {@code null}, or if {@code field} is not {@code static}.
105      * @see Field#get(Object)
106      */
107     public static Object getStaticFieldValue(final Field field) {
108         return getFieldValue(field, null);
109     }
110 
111     /**
112      * Sets the value of a {@link Field}, making it accessible if required.
113      *
114      * @param field    the Field to write a value to (must not be {@code null}).
115      * @param instance the instance to write the value to or {@code null} only if the field is static.
116      * @param value    the (possibly wrapped) value to write to the field.
117      * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
118      *                              {@code field} is not {@code static}.
119      * @see Field#set(Object, Object)
120      */
121     public static void setFieldValue(final Field field, final Object instance, final Object value) {
122         makeAccessible(field);
123         if (!Modifier.isStatic(field.getModifiers())) {
124             Objects.requireNonNull(instance, "No instance given for non-static field");
125         }
126         try {
127             field.set(instance, value);
128         } catch (final IllegalAccessException e) {
129             throw new UnsupportedOperationException(e);
130         }
131     }
132 
133     /**
134      * Sets the value of a static {@link Field}, making it accessible if required.
135      *
136      * @param field the Field to write a value to (must not be {@code null}).
137      * @param value the (possibly wrapped) value to write to the field.
138      * @throws NullPointerException if {@code field} is {@code null}, or if {@code field} is not {@code static}.
139      * @see Field#set(Object, Object)
140      */
141     public static void setStaticFieldValue(final Field field, final Object value) {
142         setFieldValue(field, null, value);
143     }
144 
145     /**
146      * Gets the default (no-arg) constructor for a given class.
147      *
148      * @param clazz the class to find a constructor for
149      * @param <T>   the type made by the constructor
150      * @return the default constructor for the given class
151      * @throws IllegalStateException if no default constructor can be found
152      */
153     public static <T> Constructor<T> getDefaultConstructor(final Class<T> clazz) {
154         Objects.requireNonNull(clazz, "No class provided");
155         try {
156             final Constructor<T> constructor = clazz.getDeclaredConstructor();
157             makeAccessible(constructor);
158             return constructor;
159         } catch (final NoSuchMethodException ignored) {
160             try {
161                 final Constructor<T> constructor = clazz.getConstructor();
162                 makeAccessible(constructor);
163                 return constructor;
164             } catch (final NoSuchMethodException e) {
165                 throw new IllegalStateException(e);
166             }
167         }
168     }
169 
170     /**
171      * Constructs a new {@code T} object using the default constructor of its class. Any exceptions thrown by the
172      * constructor will be rethrown by this method, possibly wrapped in an
173      * {@link java.lang.reflect.UndeclaredThrowableException}.
174      *
175      * @param clazz the class to use for instantiation.
176      * @param <T>   the type of the object to construct.
177      * @return a new instance of T made from its default constructor.
178      * @throws IllegalArgumentException if the given class is abstract, an interface, an array class, a primitive type,
179      *                                  or void
180      * @throws IllegalStateException    if access is denied to the constructor, or there are no default constructors
181      */
182     public static <T> T instantiate(final Class<T> clazz) {
183         Objects.requireNonNull(clazz, "No class provided");
184         final Constructor<T> constructor = getDefaultConstructor(clazz);
185         try {
186             return constructor.newInstance();
187         } catch (final NoClassDefFoundError e) {
188             // LOG4J2-1051
189             // On platforms like Google App Engine and Android, some JRE classes are not supported: JMX, JNDI, etc.
190             throw new IllegalArgumentException(e);
191         } catch (final InstantiationException e) {
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 }