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 member the Member to check for public accessibility (must not be {@code null}).
041     * @return {@code true} if {@code member} is public and contained in a public class.
042     * @throws NullPointerException if {@code member} is {@code null}.
043     */
044    public static <T extends AccessibleObject & Member> boolean isAccessible(final T member) {
045        Objects.requireNonNull(member, "No member provided");
046        return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers());
047    }
048
049    /**
050     * Makes a {@link Member} {@link AccessibleObject#isAccessible() accessible} if the member is not public.
051     *
052     * @param member the Member to make accessible (must not be {@code null}).
053     * @throws NullPointerException if {@code member} is {@code null}.
054     */
055    public static <T extends AccessibleObject & Member> void makeAccessible(final T member) {
056        if (!isAccessible(member) && !member.isAccessible()) {
057            member.setAccessible(true);
058        }
059    }
060
061    /**
062     * Makes a {@link Field} {@link AccessibleObject#isAccessible() accessible} if it is not public or if it is final.
063     *
064     * <p>Note that using this method to make a {@code final} field writable will most likely not work very well due to
065     * compiler optimizations and the like.</p>
066     *
067     * @param field the Field to make accessible (must not be {@code null}).
068     * @throws NullPointerException if {@code field} is {@code null}.
069     */
070    public static void makeAccessible(final Field field) {
071        Objects.requireNonNull(field, "No field provided");
072        if ((!isAccessible(field) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
073            field.setAccessible(true);
074        }
075    }
076
077    /**
078     * Gets the value of a {@link Field}, making it accessible if required.
079     *
080     * @param field    the Field to obtain a value from (must not be {@code null}).
081     * @param instance the instance to obtain the field value from or {@code null} only if the field is static.
082     * @return the value stored by the field.
083     * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
084     *                              {@code field} is not {@code static}.
085     * @see Field#get(Object)
086     */
087    public static Object getFieldValue(final Field field, final Object instance) {
088        makeAccessible(field);
089        if (!Modifier.isStatic(field.getModifiers())) {
090            Objects.requireNonNull(instance, "No instance given for non-static field");
091        }
092        try {
093            return field.get(instance);
094        } catch (final IllegalAccessException e) {
095            throw new UnsupportedOperationException(e);
096        }
097    }
098
099    /**
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}