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.titilink.camel.rest.util.CommonUtils.java

/**
 * ?//from  www . j a  v  a 2s. co m
 *
 * @param instance
 * @param <T>
 * @throws OperationException
 */
private static <T> void trimAndCheckParameter(T instance) throws OperationException {
    if (null == instance) {
        return;
    }

    if ((!instance.getClass().getName().startsWith(PACKAGE_NAME_PREFIX)) && instance.getClass() != List.class) {
        return;
    }

    Field[] fields = instance.getClass().getDeclaredFields();
    String value = null;
    for (Field field : fields) {
        field.setAccessible(true);

        try {
            if (field.getType().getName().startsWith(PACKAGE_NAME_PREFIX)) {
                trimAndCheckParameter(field.get(instance));
            } else if (field.getType() == String.class) {
                value = (String) field.get(instance);
                if (null != value) {
                    field.set(instance, value.trim());
                }
            } else if (field.getType() == List.class) {
                List<T> list = (List<T>) field.get(instance);
                if (null != list) {
                    for (T t : list) {
                        trimAndCheckParameter(t);
                    }
                }
            }
        } catch (OperationException e) {
            LOGGER.error("trimAndCheckParameter method error, trim exception field={}, instance={}", field,
                    instance);

            LOGGER.error("trimAndCheckParameter method error, trim exception e=", e);
            throw new OperationException(Status.CLIENT_ERROR_BAD_REQUEST.getCode(), e.getErrorCode(),
                    e.getMessage());
        } catch (Exception e) {
            LOGGER.error("trimAndCheckParameter method error, trim exception field={}, instance={}", field,
                    instance);
            LOGGER.error("trimAndCheckParameter method error, trim exception e=", e);
            throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
        }
    }

    // ??
    checkParameter(instance);
}

From source file:edu.usu.sdl.openstorefront.core.util.EntityUtil.java

/**
 * This only support updating NON-composite keys.
 *
 * @param <T>/*  www  .  j  a  va2 s. c o  m*/
 * @param entity
 * @param value
 */
public static <T extends BaseEntity> void updatePKFieldValue(T entity, String value) {
    Field field = getPKField(entity);
    if (field != null) {
        if (isSubClass("BasePK", field.getType()) == false) {
            try {
                field.setAccessible(true);
                field.set(entity, value);
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                throw new OpenStorefrontRuntimeException(
                        "Unable to set value on " + entity.getClass().getName(), "Check entity passed in.");
            }
        } else {
            throw new OpenStorefrontRuntimeException(
                    "Set value on Composite PK is not supported. Entity:  " + entity.getClass().getName(),
                    "Check entity passed in.");
        }
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find PK for enity: " + entity.getClass().getName(),
                "Check entity passed in.");
    }
}

From source file:de.Keyle.MyPet.util.BukkitUtil.java

@SuppressWarnings("unchecked")
public static boolean unregisterMyPetEntities() {
    DebugLogger.info("Unregister MyPet entities");
    try {/*from   w  ww  .  j a  va2 s. co m*/
        Field EntityTypes_d = EntityTypes.class.getDeclaredField("d");
        Field EntityTypes_f = EntityTypes.class.getDeclaredField("f");
        EntityTypes_d.setAccessible(true);
        EntityTypes_f.setAccessible(true);

        Map<Class, String> d = (Map) EntityTypes_d.get(EntityTypes_d);
        Map<Class, Integer> f = (Map) EntityTypes_f.get(EntityTypes_f);

        Iterator dIterator = d.keySet().iterator();
        while (dIterator.hasNext()) {
            Class clazz = (Class) dIterator.next();
            if (clazz.getCanonicalName().startsWith("de.Keyle.MyPet")) {
                dIterator.remove();
            }
        }

        Iterator fIterator = f.keySet().iterator();
        while (fIterator.hasNext()) {
            Class clazz = (Class) fIterator.next();
            if (clazz.getCanonicalName().startsWith("de.Keyle.MyPet")) {
                fIterator.remove();
            }
        }

        return true;
    } catch (Exception e) {
        DebugLogger.severe("error while unregistering MyPet entities");
        DebugLogger.severe(e.getMessage());
        return false;
    }
}

From source file:com.fengduo.bee.commons.util.ObjectUtils.java

/**
 * string?trim?/*from  w w w . ja v  a 2  s  . c o  m*/
 * 
 * @param object
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static void trimStringField(Object object, Class<?> clazz) throws Exception {
    if (object instanceof Map<?, ?>) {
        Map<Object, Object> target = new HashMap<Object, Object>();
        for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();

            if (key instanceof String) {
                key = StringUtils.trim((String) key);
            } else {
                trim(key);
            }

            if (value instanceof String) {
                value = StringUtils.trim((String) value);
                value = StringUtils.replace((String) value, "\"", StringUtils.EMPTY);
            } else {
                trim(value);
            }
            target.put(key, value);
        }
        ((Map<?, ?>) object).clear();
        ((Map) object).putAll((Map) target);
        return;
    }
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.getType() == String.class) {
            boolean isFoolback = false;
            if (field.isAccessible() == false) {
                isFoolback = true;
                field.setAccessible(true);
            }
            String value = (String) field.get(object);
            if (StringUtils.isNotEmpty(value)) {
                value = value.trim();
                field.set(object, value);
            }
            if (isFoolback) {
                field.setAccessible(false);
            }
        }
    }
}

From source file:de.Keyle.MyPet.util.BukkitUtil.java

@SuppressWarnings("unchecked")
public static boolean registerMyPetEntity(Class<? extends EntityMyPet> myPetEntityClass, String entityTypeName,
        int entityTypeId) {
    try {/*from w w  w. ja  v  a  2  s . c  o  m*/
        Field EntityTypes_d = EntityTypes.class.getDeclaredField("d");
        Field EntityTypes_f = EntityTypes.class.getDeclaredField("f");
        EntityTypes_d.setAccessible(true);
        EntityTypes_f.setAccessible(true);

        Map<Class, String> d = (Map) EntityTypes_d.get(EntityTypes_d);
        Map<Class, Integer> f = (Map) EntityTypes_f.get(EntityTypes_f);

        Iterator cIterator = d.keySet().iterator();
        while (cIterator.hasNext()) {
            Class clazz = (Class) cIterator.next();
            if (clazz.getCanonicalName().equals(myPetEntityClass.getCanonicalName())) {
                cIterator.remove();
            }
        }

        Iterator eIterator = f.keySet().iterator();
        while (eIterator.hasNext()) {
            Class clazz = (Class) eIterator.next();
            if (clazz.getCanonicalName().equals(myPetEntityClass.getCanonicalName())) {
                eIterator.remove();
            }
        }

        d.put(myPetEntityClass, entityTypeName);
        f.put(myPetEntityClass, entityTypeId);

        return true;
    } catch (Exception e) {
        DebugLogger.severe("error while registering " + myPetEntityClass.getCanonicalName());
        DebugLogger.severe(e.getMessage());
        return false;
    }
}

From source file:com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentialsTest.java

private static void setPrivateField(GoogleRobotPrivateKeyCredentials credentials, String fieldName,
        Object value) throws NoSuchFieldException, IllegalAccessException {
    Field field = GoogleRobotPrivateKeyCredentials.class.getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(credentials, value);//from  w ww  .j  av  a 2s .c o m
}

From source file:ee.ria.xroad.common.message.SoapUtils.java

static Object getFieldValue(Field field, Object object) {
    field.setAccessible(true);
    try {//w  ww.  ja v a  2 s.c  o  m
        return field.get(object);
    } catch (Exception e) {
        throw translateException(e);
    }
}

From source file:ReflectionUtils.java

/**
 * ,DeclaredField./*from  w w  w.  j a  v  a 2s  .co m*/
 */
protected static void makeAccessible(final Field field) {
    if (!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
        field.setAccessible(true);
    }
}

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

/**
 * Returns field of class//from  w w w . ja  v  a  2  s  . c  o m
 * 
 * @param entityClass class
 * @param fieldName field
 * @return Field
 */
private static Field getField(Class<?> entityClass, String fieldName) {
    try {
        Field field = entityClass.getDeclaredField(fieldName);
        field.setAccessible(true);
        return field;
    } catch (SecurityException e) {
        return null;
    } catch (NoSuchFieldException e) {
        Class<?> superClass = entityClass.getSuperclass();
        if (superClass.equals(Object.class)) {
            return null;
        } else {
            return getField(superClass, fieldName);
        }
    }
}

From source file:fr.paris.lutece.plugins.contextinclude.service.parameter.ContextParameterService.java

/**
 * Depopulate.// w  w  w  .j a v  a  2  s . com
 *
 * @param contextParameter the context parameter
 * @return the map
 */
private static Map<String, Object> depopulate(IContextParameter contextParameter) {
    Map<String, Object> mapAttributes = new HashMap<String, Object>();

    for (java.lang.reflect.Field field : ContextParameter.class.getDeclaredFields()) {
        ContextAttribute attribute = field.getAnnotation(ContextAttribute.class);

        if (attribute != null) {
            String strAttributeKey = attribute.value();

            try {
                field.setAccessible(true);

                Object attributeValue = ReflectionUtils.getField(field, contextParameter);
                mapAttributes.put(strAttributeKey, attributeValue);
            } catch (SecurityException e) {
                AppLogService.error(e);
            }
        }
    }

    return mapAttributes;
}