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:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * Compares to consume fields of two object of the same type Note this won't
 * work with proxy object.//  w w w.ja  v  a 2s .co m
 *
 * @param original
 * @param compare
 * @return compare value (0 if equals)
 */
public static int compareConsumeFields(Object original, Object compare) {
    int value = 0;
    if (original != null && compare == null) {
        value = -1;
    } else if (original == null && compare != null) {
        value = 1;
    } else if (original != null && compare != null) {
        if (original.getClass().isInstance(compare)) {
            List<Field> fields = getAllFields(original.getClass());
            for (Field field : fields) {
                ConsumeField consume = (ConsumeField) field.getAnnotation(ConsumeField.class);
                if (consume != null) {
                    try {
                        field.setAccessible(true);
                        value = compareObjects((Comparable) field.get(original),
                                (Comparable) field.get(compare));
                        if (value != 0) {
                            break;
                        }
                    } catch (IllegalArgumentException | IllegalAccessException ex) {
                        throw new OpenStorefrontRuntimeException("Can't compare object fields", ex);
                    }
                }
            }
        } else {
            throw new OpenStorefrontRuntimeException("Can't compare different object types", "Check objects");
        }
    }
    return value;
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void escapeHTMLString(Object escapeObject) {
    String oldData = "";
    String newData = "";
    try {// www. j  a va 2 s .c o m
        if (escapeObject != null) {
            Class escapeClass = escapeObject.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(escapeObject) != null) {
                        oldData = f.get(escapeObject).toString();
                        newData = StringEscapeUtils.escapeSql(oldData);
                        f.set(escapeObject, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(escapeObject);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = StringEscapeUtils.escapeSql(tmpArr[i]);
                            }
                            f.set(escapeObject, tmpArr);
                        }
                    }
                } else if (f.get(escapeObject) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(escapeObject);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, StringEscapeUtils.escapeSql(tmpList.get(i).toString()));
                        }
                    }
                    f.set(escapeObject, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void trimString(Object obj, boolean isLower) {
    String oldData = "";
    String newData = "";
    try {//w  w w . ja va2 s.c o  m
        if (obj != null) {
            Class escapeClass = obj.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(obj) != null) {
                        oldData = f.get(obj).toString();
                        newData = isLower ? oldData.trim().toLowerCase() : oldData.trim();
                        f.set(obj, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(obj);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = isLower ? tmpArr[i].trim().toLowerCase() : tmpArr[i].trim();
                            }
                            f.set(obj, tmpArr);
                        }
                    }
                } else if (f.get(obj) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(obj);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, isLower ? tmpList.get(i).toString().trim().toLowerCase()
                                    : tmpList.get(i).toString().trim());
                        }
                    }
                    f.set(obj, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Retrieves the statistics data from an Alfresco default {@code DefaultSimpleCache}
 *
 * @param defaultSimpleCache/*from   w  ww.  j  a  va2  s  . co  m*/
 *            the simple cache instance
 * @return the statistics object
 * @throws Exception
 *             if the reflective access fails for any reason
 */
public static Object getDefaultSimpleCacheStats(final DefaultSimpleCache<?, ?> defaultSimpleCache)
        throws Exception {
    ParameterCheck.mandatory("defaultSimpleCache", defaultSimpleCache);

    final Field googleCacheField = DefaultSimpleCache.class.getDeclaredField("cache");
    // will fail in Java 9 but no other way due to private visibility and lack of accessor
    googleCacheField.setAccessible(true);
    final Object googleCache = googleCacheField.get(defaultSimpleCache);

    final CacheStats stats = ((Cache<?, ?>) googleCache).stats();
    return stats;
}

From source file:io.github.benas.randombeans.util.ReflectionUtils.java

/**
 * Get the value (accessible or not accessible) of a field of a target object.
 *
 * @param object instance to get the field of
 * @param field  field to get the value of
 * @throws IllegalAccessException if field can not be accessed
 *//*from w w  w .j  a v a 2  s. c om*/
public static Object getFieldValue(final Object object, final Field field) throws IllegalAccessException {
    boolean access = field.isAccessible();
    field.setAccessible(true);
    Object value = field.get(object);
    field.setAccessible(access);
    return value;
}

From source file:net.minecraftforge.common.util.EnumHelper.java

private static void blankField(Class<?> enumClass, String fieldName) throws Exception {
    for (Field field : Class.class.getDeclaredFields()) {
        if (field.getName().contains(fieldName)) {
            field.setAccessible(true);
            setFailsafeFieldValue(field, enumClass, null);
            break;
        }/* ww w  .j  a v  a2  s  .  c om*/
    }
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Sets entity's field's value/*from  w  w w. j a  va 2  s.co  m*/
 * 
 * @param entity entity
 * @param fieldName field
 * @param value value
 * @throws FoursquareApiException when something unexpected happens
 */
private static void setEntityFieldValue(FoursquareEntity entity, String fieldName, Object value)
        throws FoursquareApiException {
    java.lang.reflect.Field fieldProperty;
    try {
        fieldProperty = getField(entity.getClass(), fieldName);
        fieldProperty.setAccessible(true);
        fieldProperty.set(entity, value);
    } catch (Exception e) {
        throw new FoursquareApiException(e);
    }
}

From source file:org.orderofthebee.addons.support.tools.repo.caches.CacheLookupUtils.java

/**
 * Retrieves the statistics data from an Alfresco Enterprise Edition {@code HazelcastSimpleCache}
 *
 * @param simpleCache// www .j  av  a  2  s .c o  m
 *            the simple cache
 * @return the statistics object
 * @throws Exception
 *             if the reflective access fails for any reason
 */
public static Object getHzSimpleCacheStats(final SimpleCache<?, ?> simpleCache) throws Exception {
    ParameterCheck.mandatory("simpleCache", simpleCache);

    final Field mapField = simpleCache.getClass().getDeclaredField("map");
    // will fail in Java 9 but no other way due to private visibility, Enterprise-only class and lack of accessor
    mapField.setAccessible(true);
    final Object internalMap = mapField.get(simpleCache);
    final Method mapStatsGetter = internalMap.getClass().getMethod("getLocalMapStats");
    final Object stats = mapStatsGetter.invoke(internalMap);

    return stats;
}

From source file:org.openmrs.module.distrotools.test.TestUtils.java

/**
 * Modifies a constant in a constants class. If the constant is final and not based on a runtime expression, then
 * it's value will have been inlined by the compiler and this method will have no effect.
 * @param constantsClass the class of constants
 * @param fieldName the field name of the constant
 * @param newValue the new value for the constant
 * @throws Exception if field not found or couldn't be modified
 *//*from  ww w.  j  a va2s  . c  o  m*/
public static void modifyConstant(Class<?> constantsClass, String fieldName, Object newValue) throws Exception {
    Field field = constantsClass.getDeclaredField(fieldName);
    field.setAccessible(true);

    int existingModifiers = field.getModifiers();

    // Remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, existingModifiers & ~Modifier.FINAL);

    field.set(null, newValue);

    // Reset previous modifiers
    modifiersField.setInt(field, existingModifiers);
}