Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

In this page you can find the example usage for java.lang Class getDeclaredField.

Prototype

@CallerSensitive
public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

Usage

From source file:io.pivotal.spring.xd.jdbcgpfdist.TestUtils.java

@SuppressWarnings("unchecked")
public static <T> T readField(String name, Object target) throws Exception {
    Field field = null;//from   w w  w.  ja  va  2s  . co m
    Class<?> clazz = target.getClass();
    do {
        try {
            field = clazz.getDeclaredField(name);
        } catch (Exception ex) {
        }

        clazz = clazz.getSuperclass();
    } while (field == null && !clazz.equals(Object.class));

    if (field == null)
        throw new IllegalArgumentException(
                "Cannot find field '" + name + "' in the class hierarchy of " + target.getClass());
    field.setAccessible(true);
    return (T) field.get(target);
}

From source file:Main.java

public static Field getField(Class<?> targetClass, String name) {
    if (targetClass == null || TextUtils.isEmpty(name))
        return null;
    try {// w w  w  . java  2 s .  c om
        return targetClass.getDeclaredField(name);
    } catch (SecurityException e) {
        // ignore
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static void setField(Object object, String fieldName, Object fieldValue) {
    Class<?> objectClass = object.getClass();
    if (objectClass != null) {
        try {/*from   w w  w.j  a  v  a 2  s.co  m*/
            Field field = objectClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            Type type = field.getGenericType();

            //This is bad, but dear God I can't figure out how to convert a runtime Type to its actual type through reflection. I know how in C#....
            if (type.toString().toLowerCase().contains("short")) {
                fieldValue = Short.parseShort((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("integer")) {
                fieldValue = Integer.parseInt((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("long")) {
                fieldValue = Long.parseLong((String) fieldValue);
            }

            else if (type.toString().toLowerCase().contains("boolean")) {
                fieldValue = "1".equals(fieldValue); //Java, you're the worst language. And SQLite isn't helping.
            }

            field.set(object, fieldValue);
        }

        catch (NoSuchFieldException e) {
            return;
        }

        catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:Main.java

/**
 * get GridView vertical spacing/*from  w  ww .  j av a  2s  .co  m*/
 * 
 * @param view
 * @return
 */
public static int getGridViewVerticalSpacing(GridView view) {
    // get mVerticalSpacing by android.widget.GridView
    Class<?> demo = null;
    int verticalSpacing = 0;
    try {
        demo = Class.forName(CLASS_NAME_GRID_VIEW);
        Field field = demo.getDeclaredField(FIELD_NAME_VERTICAL_SPACING);
        field.setAccessible(true);
        verticalSpacing = (Integer) field.get(view);
        return verticalSpacing;
    } catch (Exception e) {
        /**
         * accept all exception, include ClassNotFoundException, NoSuchFieldException, InstantiationException,
         * IllegalArgumentException, IllegalAccessException, NullPointException
         */
        e.printStackTrace();
    }
    return verticalSpacing;
}

From source file:com.codeabovelab.dm.common.utils.ProcessUtils.java

/**
 * Get system ProcessID of specified process. <p/>
 * Currently it method work only on unix systems.
 * @param process//from   w  w  w .  j a  va 2 s.  c o m
 * @return PID or -1 on fail
 */
public static int getPid(Process process) {
    Class<? extends Process> clazz = process.getClass();
    try {
        Field field = clazz.getDeclaredField("pid");
        if (field.isAccessible()) {
            field.setAccessible(true);
        }
        return (int) field.get(process);
    } catch (IllegalAccessException | NoSuchFieldException e) {
        return -1;
    }
}

From source file:Main.java

public static void cleanThreadLocals(Thread thread)
        throws NoSuchFieldException, ClassNotFoundException, IllegalArgumentException, IllegalAccessException {
    if (thread == null)
        return;//from   w  ww.  j  a  v a 2  s  . com
    Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
    threadLocalsField.setAccessible(true);

    Class<?> threadLocalMapKlazz = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
    Field tableField = threadLocalMapKlazz.getDeclaredField("table");
    tableField.setAccessible(true);

    Object fieldLocal = threadLocalsField.get(thread);
    if (fieldLocal == null) {
        return;
    }
    Object table = tableField.get(fieldLocal);

    int threadLocalCount = Array.getLength(table);

    for (int i = 0; i < threadLocalCount; i++) {
        Object entry = Array.get(table, i);
        if (entry != null) {
            Field valueField = entry.getClass().getDeclaredField("value");
            valueField.setAccessible(true);
            Object value = valueField.get(entry);
            if (value != null) {

                if ("java.util.concurrent.ConcurrentLinkedQueue".equals(value.getClass().getName())
                        || "java.util.concurrent.ConcurrentHashMap".equals(value.getClass().getName())) {
                    valueField.set(entry, null);
                }
            }

        }
    }
}

From source file:com.codebase.foundation.classloader.xbean.ClassLoaderUtil.java

/**
 * Clears the caches maintained by the SunVM object stream implementation.  This method uses reflection and
 * setAccessable to obtain access to the Sun cache.  The cache is locked with a synchronize monitor and cleared.
 * This method completely clears the class loader cache which will impact performance of object serialization.
 * @param clazz the name of the class containing the cache field
 * @param fieldName the name of the cache field
 *///from  ww w. ja v a  2 s . c om
@SuppressWarnings("all")
public static void clearSunSoftCache(Class clazz, String fieldName) {
    Map cache = null;
    try {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        cache = (Map) field.get(null);
    } catch (Throwable ignored) {
        // there is nothing a user could do about this anyway
    }

    if (cache != null) {
        synchronized (cache) {
            cache.clear();
        }
    }
}

From source file:com.abiquo.model.util.ModelTransformer.java

private static boolean fieldExist(final String fieldName, final Class clazz) throws Exception {
    try {/*from  w w w  . j a v  a2s.c o  m*/
        return clazz.getDeclaredField(fieldName) != null;
    } catch (NoSuchFieldException ex) {
        return false;
    }
}

From source file:Main.java

private static Field getField(String fieldName, Class<?> objectClass) throws NoSuchFieldException {
    Field field = null;// w w w.j av a 2s.c  om
    while (objectClass != null && field == null) {
        try {
            field = objectClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            objectClass = objectClass.getSuperclass();
        }
    }
    if (field != null) {
        field.setAccessible(true);
    } else {
        throw new NoSuchFieldException(fieldName);
    }
    return field;
}

From source file:org.mongojack.internal.util.JacksonAccessor.java

private static Field findField(Class clazz, String name) {
    try {// w ww  .  j a  va 2 s .c om
        Field field = clazz.getDeclaredField(name);
        field.setAccessible(true);
        return field;
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
}