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    
018    package org.apache.logging.log4j.core.util;
019    
020    import java.lang.reflect.AccessibleObject;
021    import java.lang.reflect.Constructor;
022    import java.lang.reflect.Field;
023    import java.lang.reflect.InvocationTargetException;
024    import java.lang.reflect.Member;
025    import java.lang.reflect.Modifier;
026    
027    /**
028     * Utility class for performing common reflective operations.
029     *
030     * @since 2.1
031     */
032    public final class ReflectionUtil {
033        private ReflectionUtil() {
034        }
035    
036        /**
037         * Indicates whether or not a {@link Member} is both public and is contained in a public class.
038         *
039         * @param member the Member to check for public accessibility (must not be {@code null}).
040         * @return {@code true} if {@code member} is public and contained in a public class.
041         * @throws NullPointerException if {@code member} is {@code null}.
042         */
043        public static <T extends AccessibleObject & Member> boolean isAccessible(final T member) {
044            Assert.requireNonNull(member, "No member provided");
045            return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(member.getDeclaringClass().getModifiers());
046        }
047    
048        /**
049         * Makes a {@link Member} {@link AccessibleObject#isAccessible() accessible} if the member is not public.
050         *
051         * @param member the Member to make accessible (must not be {@code null}).
052         * @throws NullPointerException if {@code member} is {@code null}.
053         */
054        public static <T extends AccessibleObject & Member> void makeAccessible(final T member) {
055            if (!isAccessible(member) && !member.isAccessible()) {
056                member.setAccessible(true);
057            }
058        }
059    
060        /**
061         * Makes a {@link Field} {@link AccessibleObject#isAccessible() accessible} if it is not public or if it is final.
062         *
063         * <p>Note that using this method to make a {@code final} field writable will most likely not work very well due to
064         * compiler optimizations and the like.</p>
065         *
066         * @param field the Field to make accessible (must not be {@code null}).
067         * @throws NullPointerException if {@code field} is {@code null}.
068         */
069        public static void makeAccessible(final Field field) {
070            Assert.requireNonNull(field, "No field provided");
071            if ((!isAccessible(field) || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
072                field.setAccessible(true);
073            }
074        }
075    
076        /**
077         * Gets the value of a {@link Field}, making it accessible if required.
078         *
079         * @param field    the Field to obtain a value from (must not be {@code null}).
080         * @param instance the instance to obtain the field value from or {@code null} only if the field is static.
081         * @return the value stored by the field.
082         * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
083         *                              {@code field} is not {@code static}.
084         * @see Field#get(Object)
085         */
086        public static Object getFieldValue(final Field field, final Object instance) {
087            makeAccessible(field);
088            if (!Modifier.isStatic(field.getModifiers())) {
089                Assert.requireNonNull(instance, "No instance given for non-static field");
090            }
091            try {
092                return field.get(instance);
093            } catch (final IllegalAccessException e) {
094                throw new UnsupportedOperationException(e);
095            }
096        }
097    
098        /**
099         * Gets the value of a static {@link Field}, making it accessible if required.
100         *
101         * @param field the Field to obtain a value from (must not be {@code null}).
102         * @return the value stored by the static field.
103         * @throws NullPointerException if {@code field} is {@code null}, or if {@code field} is not {@code static}.
104         * @see Field#get(Object)
105         */
106        public static Object getStaticFieldValue(final Field field) {
107            return getFieldValue(field, null);
108        }
109    
110        /**
111         * Sets the value of a {@link Field}, making it accessible if required.
112         *
113         * @param field    the Field to write a value to (must not be {@code null}).
114         * @param instance the instance to write the value to or {@code null} only if the field is static.
115         * @param value    the (possibly wrapped) value to write to the field.
116         * @throws NullPointerException if {@code field} is {@code null}, or if {@code instance} is {@code null} but
117         *                              {@code field} is not {@code static}.
118         * @see Field#set(Object, Object)
119         */
120        public static void setFieldValue(final Field field, final Object instance, final Object value) {
121            makeAccessible(field);
122            if (!Modifier.isStatic(field.getModifiers())) {
123                Assert.requireNonNull(instance, "No instance given for non-static field");
124            }
125            try {
126                field.set(instance, value);
127            } catch (final IllegalAccessException e) {
128                throw new UnsupportedOperationException(e);
129            }
130        }
131    
132        /**
133         * Sets the value of a static {@link Field}, making it accessible if required.
134         *
135         * @param field the Field to write a value to (must not be {@code null}).
136         * @param value the (possibly wrapped) value to write to the field.
137         * @throws NullPointerException if {@code field} is {@code null}, or if {@code field} is not {@code static}.
138         * @see Field#set(Object, Object)
139         */
140        public static void setStaticFieldValue(final Field field, final Object value) {
141            setFieldValue(field, null, value);
142        }
143    
144        /**
145         * Gets the default (no-arg) constructor for a given class.
146         *
147         * @param clazz the class to find a constructor for
148         * @param <T>   the type made by the constructor
149         * @return the default constructor for the given class
150         * @throws IllegalStateException if no default constructor can be found
151         */
152        public static <T> Constructor<T> getDefaultConstructor(final Class<T> clazz) {
153            Assert.requireNonNull(clazz, "No class provided");
154            try {
155                final Constructor<T> constructor = clazz.getDeclaredConstructor();
156                makeAccessible(constructor);
157                return constructor;
158            } catch (final NoSuchMethodException ignored) {
159                try {
160                    final Constructor<T> constructor = clazz.getConstructor();
161                    makeAccessible(constructor);
162                    return constructor;
163                } catch (final NoSuchMethodException e) {
164                    throw new IllegalStateException(e);
165                }
166            }
167        }
168    
169        /**
170         * Constructs a new {@code T} object using the default constructor of its class. Any exceptions thrown by the
171         * constructor will be rethrown by this method, possibly wrapped in an
172         * {@link java.lang.reflect.UndeclaredThrowableException}.
173         *
174         * @param clazz the class to use for instantiation.
175         * @param <T>   the type of the object to construct.
176         * @return a new instance of T made from its default constructor.
177         * @throws IllegalArgumentException if the given class is abstract, an interface, an array class, a primitive type,
178         *                                  or void
179         * @throws IllegalStateException    if access is denied to the constructor, or there are no default constructors
180         */
181        public static <T> T instantiate(final Class<T> clazz) {
182            Assert.requireNonNull(clazz, "No class provided");
183            final Constructor<T> constructor = getDefaultConstructor(clazz);
184            try {
185                return constructor.newInstance();
186            } catch (final InstantiationException e) {
187                throw new IllegalArgumentException(e);
188            } catch (final IllegalAccessException e) {
189                throw new IllegalStateException(e);
190            } catch (final InvocationTargetException e) {
191                Throwables.rethrow(e.getCause());
192                throw new InternalError("Unreachable");
193            }
194        }
195    }