001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache license, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the license for the specific language governing permissions and
015 * limitations under the license.
016 */
017
018package org.apache.logging.log4j.core.util;
019
020import java.lang.reflect.AccessibleObject;
021import java.lang.reflect.Constructor;
022import java.lang.reflect.Field;
023import java.lang.reflect.InvocationTargetException;
024import java.lang.reflect.Member;
025import java.lang.reflect.Modifier;
026import java.util.Objects;
027
028/**
029 * Utility class for performing common reflective operations.
030 *
031 * @since 2.1
032 */
033public final class ReflectionUtil {
034    private ReflectionUtil() {
035    }
036
037    /**
038     * Indicates whether or not a {@link Member} is both public and is contained in a public class.
039     *
040     * @param <T> type of the object whose accessibility to test
041     * @param member the Member to check for public accessibility (must not be {@code null}).
042     * @return {@code true} if {@code member} is public and contained in a public class.
043     * @throws NullPointerException if {@code member} is {@code null}.
044     */
045    public static <T extends AccessibleObject & Member> boolean isAccessible(final T member) {
046        Objects.requireNonNull(member, "No member provided");
047        return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers());
048    }
049
050    /**
051     * Makes a {@link Member} {@link AccessibleObject#isAccessible() accessible} if the member is not public.
052     *
053     * @param <T> type of the object to make accessible
054     * @param member the Member to make accessible (must not be {@code null}).
055     * @throws NullPointerException if {@code member} is {@code null}.
056     */
057    public static <T extends AccessibleObject & Member> void makeAccessible(final T member) {
058        if (!isAccessible(member) && !member.isAccessible()) {
059            member.setAccessible(true);
060        }
061    }
062
063    /**
064     * Makes a {@link Field} {@link AccessibleObject#isAccessible() accessible} if it is not public or if it is final.
065     *
066     * <p>Note that using this method to make a {@code final} field writable will most likely not work very well due to
067     * compiler optimizations and the like.</p>
068     *
069     * @param field the Field to make accessible (must not be {@code null}).
070     * @throws NullPointerException if {@code field} is {@code null}.
071     */
072    public static void makeAccessible(final Field field) {
073        Objects.requireNonNull(field, "No field provided");
074        if ((!isAccessible(field) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
075            field.setAccessible(true);
076        }
077    }
078
079    /**
080     * Gets the value of a {@link Field}, making it accessible if required.
081     *
082     * @param field    the Field to obtain a value from (must not be {@code null}).
083     * @param instance the instance to obtain the field value from or {@code null} only if the field is static.
084     * @return the value stored by the field.
085     * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
086     *                              {@code field} is not {@code static}.
087     * @see Field#get(Object)
088     */
089    public static Object getFieldValue(final Field field, final Object instance) {
090        makeAccessible(field);
091        if (!Modifier.isStatic(field.getModifiers())) {
092            Objects.requireNonNull(instance, "No instance given for non-static field");
093        }
094        try {
095            return field.get(instance);
096        } catch (final IllegalAccessException e) {
097            throw new UnsupportedOperationException(e);
098        }
099    }
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 LinkageError | 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}