Example usage for java.lang.reflect Field setAccessible

List of usage examples for java.lang.reflect Field setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.hortonworks.minicluster.util.ReflectionUtils.java

/**
 *
 * @param clazz//  www.  j  a  v  a2s.  c  o  m
 * @param fieldName
 * @return
 */
public static Field getFieldAndMakeAccessible(Class<?> clazz, String fieldName) {
    ObjectAssertUtils.assertNotNull(clazz);
    StringAssertUtils.assertNotEmptyAndNoSpaces(fieldName);
    Class<?> searchType = clazz;
    while (!Object.class.equals(searchType) && searchType != null) {
        Field[] fields = searchType.getDeclaredFields();
        for (Field field : fields) {
            if (fieldName == null || fieldName.equals(field.getName())) {
                field.setAccessible(true);
                return field;
            }
        }
        searchType = searchType.getSuperclass();
    }
    return null;
}

From source file:com.sailing.hrm.common.util.ReflectionUtils.java

/**
 * ?, ?DeclaredField,    ?.// www. j  ava 2s  . c o m
 * 
 * ?Object?, null.
 */
public static Field getAccessibleField(final Object obj, final String fieldName) {
    Assert.assertNotNull("object?", obj);
    Assert.assertNotNull("fieldName?", fieldName);
    Assert.assertTrue("fieldName?", StringUtil.notNull(fieldName.trim()));
    for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
            .getSuperclass()) {
        try {
            Field field = superClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field;
        } catch (NoSuchFieldException e) {//NOSONAR
            // Field??,?
        }
    }
    return null;
}

From source file:Main.java

/**
 * Swing menus are looking pretty bad on Linux when the GTK LaF is used (See
 * bug #6925412). It will most likely never be fixed anytime soon so this
 * method provides a workaround for it. It uses reflection to change the GTK
 * style objects of Swing so popup menu borders have a minimum thickness of
 * 1 and menu separators have a minimum vertical thickness of 1.
 *///from  ww  w  .  j  a  v  a  2s .  c  o  m
public static void installGtkPopupBugWorkaround() {
    // Get current look-and-feel implementation class
    LookAndFeel laf = UIManager.getLookAndFeel();
    Class<?> lafClass = laf.getClass();

    // Do nothing when not using the problematic LaF
    if (!lafClass.getName().equals("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"))
        return;

    // We do reflection from here on. Failure is silently ignored. The
    // workaround is simply not installed when something goes wrong here
    try {
        // Access the GTK style factory
        Field field = lafClass.getDeclaredField("styleFactory");
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object styleFactory = field.get(laf);
        field.setAccessible(accessible);

        // Fix the horizontal and vertical thickness of popup menu style
        Object style = getGtkStyle(styleFactory, new JPopupMenu(), "POPUP_MENU");
        fixGtkThickness(style, "yThickness");
        fixGtkThickness(style, "xThickness");

        // Fix the vertical thickness of the popup menu separator style
        style = getGtkStyle(styleFactory, new JSeparator(), "POPUP_MENU_SEPARATOR");
        fixGtkThickness(style, "yThickness");
    } catch (Exception e) {
        // Silently ignored. Workaround can't be applied.
    }
}

From source file:Main.java

private static void setField(final Object bean, final Field field, final Object value) throws Exception {
    if (!field.isAccessible()) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            public Void run() {
                field.setAccessible(true);
                return null;
            }/*from   w  ww  . j av a 2  s. c o m*/
        });
    }
    field.set(bean, value);
}

From source file:io.github.pellse.decorator.util.reflection.ReflectionUtils.java

public static Optional<Object> getField(Object obj, Field field) {
    return Optional.ofNullable(CheckedSupplier.of(() -> {
        field.setAccessible(true);
        return field.get(obj);
    }).get());/*  w  ww.j  a  v a  2s.  c  o  m*/
}

From source file:com.searchbox.core.ref.ReflectionUtils.java

public static void copyAllFields(Object from, Object to) {
    for (Field fromField : findAllFields(from.getClass())) {
        try {/*from w  w w . ja  v  a2  s  .co  m*/
            Field toField = findUnderlying(to.getClass(), fromField.getName());
            if (toField != null) {
                toField.setAccessible(true);
                fromField.setAccessible(true);
                toField.set(to, fromField.get(from));
            }
        } catch (Exception e) {
            LOGGER.warn("Could not copye Fields.", e);
        }
    }
}

From source file:com.vivekpanyam.evolve.Utils.java

private static Field getField(Class<?> cls, String name) {
    for (Field field : cls.getDeclaredFields()) {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }//from   w w w.j  av a2 s. c om
        if (field.getName().equals(name)) {
            return field;
        }
    }
    return null;
}

From source file:com.koda.integ.hbase.util.CacheableSerializer.java

@SuppressWarnings("unchecked")
private static Field getProtectedField(Class klass, String fieldName) {
    Field field;

    try {/*from  w  w  w. j a  va  2s . c o  m*/
        field = klass.getDeclaredField(fieldName);
        field.setAccessible(true);
    } catch (Exception e) {
        throw new AssertionError(e);
    }

    return field;
}

From source file:com.redpill_linpro.springframework.beans.factory.config.EtcdPlaceholderConfigurerTests.java

@SuppressWarnings("unchecked")
private static Map<String, String> getModifiableSystemEnvironment() {
    // for os x / linux
    Class<?>[] classes = Collections.class.getDeclaredClasses();
    Map<String, String> env = System.getenv();
    for (Class<?> cl : classes) {
        if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
            try {
                Field field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                if (obj != null
                        && obj.getClass().getName().equals("java.lang.ProcessEnvironment$StringEnvironment")) {
                    return (Map<String, String>) obj;
                }//from  www.  j  av a2 s.c o m
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    // for windows
    Class<?> processEnvironmentClass;
    try {
        processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    try {
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Object obj = theCaseInsensitiveEnvironmentField.get(null);
        return (Map<String, String>) obj;
    } catch (NoSuchFieldException e) {
        // do nothing
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    try {
        Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        theEnvironmentField.setAccessible(true);
        Object obj = theEnvironmentField.get(null);
        return (Map<String, String>) obj;
    } catch (NoSuchFieldException e) {
        // do nothing
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    throw new IllegalStateException();
}

From source file:edu.mayo.cts2.framework.webapp.rest.view.jsp.Beans.java

/**
 * Inspect.//w  ww  . j ava  2s .  co  m
 *
 * @param bean the bean
 * @return the list
 */
public static List<Map.Entry<String, Object>> inspect(Object bean) {
    Map<String, Object> props = new LinkedHashMap<String, Object>();

    Class<?> clazz = bean.getClass();

    while (clazz != null) {
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String name = field.getName();

            Object value;
            try {
                value = field.get(bean);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            if (value != null) {
                props.put(name, value);
            }
        }
        clazz = clazz.getSuperclass();
    }

    List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(props.entrySet());

    Collections.sort(list, BEAN_COMPARATOR);

    return list;
}