Retrieve Value from Static Field (Belonging to No Particular Object) - Java Reflection

Java examples for Reflection:Field Value

Description

Retrieve Value from Static Field (Belonging to No Particular Object)

Demo Code

/*==================================================================================================
 RoboLib - An Expansion and Improvement Library for WPILibJ
 Copyright (C) 2015  Matthew Crocco//from w w  w . ja  va  2s  .  c om

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 =================================================================================================*/
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main{
    /**
     * Retrieve Value from Static Field (Belonging to No Particular
     * Object)
     *
     * @param klass           Containing Class
     * @param fieldName       Name of Filed
     * @param conversionClass Class to Convert Result To (prevents Type Mismatch)
     * @return Value of Static Field of type 'conversionClass'
     */
    public static <T> T getStaticField(Class<?> klass, String fieldName,
            Class<T> conversionClass) {
        conversionClass = (Class<T>) ensureClassNotPrimitive(conversionClass);

        try {
            return conversionClass.cast(retrieveField(
                    klass.getDeclaredField(fieldName), null));
        } catch (final Exception e) {
            if (klass.getSuperclass() == null)
                throw new RuntimeReflectionException(
                        "Failure to reflectively obtain Static Field '"
                                + fieldName + "'!", e);
        }

        return getStaticField(klass.getSuperclass(), fieldName,
                conversionClass);
    }
    /**
     * Returns either this class if it is not a Primitive Class or the Object Class of this Primitive
     * Class. e.g. Integer.class for int.class and Double.class for double.class. <br />
     * <br />
     * The Primitive Class is that value returned by {@link Class#getPrimitiveClass(String)}.
     *
     * @param klass
     * @return
     */
    private static Class<?> ensureClassNotPrimitive(Class<?> klass) {
        if (klass == byte.class)
            return Byte.class;
        else if (klass == short.class)
            return Short.class;
        else if (klass == int.class)
            return Integer.class;
        else if (klass == long.class)
            return Long.class;
        else if (klass == float.class)
            return Float.class;
        else if (klass == double.class)
            return Double.class;
        else
            return klass;
    }
    private static Object retrieveField(Field field, Object obj)
            throws IllegalArgumentException, IllegalAccessException {
        Object item;
        final boolean accessible = field.isAccessible();

        if (!accessible) {
            field.setAccessible(!accessible);
        }

        item = field.get(obj);

        if (!accessible) {
            field.setAccessible(accessible);
        }

        return item;
    }
}

Related Tutorials