Example usage for java.lang.reflect Field set

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public void set(Object obj, Object value) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the field represented by this Field object on the specified object argument to the specified new value.

Usage

From source file:com.haulmont.cuba.core.entity.BaseEntityInternalAccess.java

public static void setValueForHolder(Entity entity, String attribute, @Nullable Object value) {
    Preconditions.checkNotNullArgument(entity, "entity is null");
    Field field = FieldUtils.getField(entity.getClass(), String.format("_persistence_%s_vh", attribute), true);
    if (field == null)
        return;/*from   w ww.  j a v a  2  s.  co  m*/
    try {
        field.set(entity, value);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                String.format("Unable to set value to %s.%s", entity.getClass().getSimpleName(), attribute), e);
    }
}

From source file:com.taobao.android.builder.tasks.manager.transform.TransformManager.java

public static void replaceTransformTask(TransformTask transformTask, Transform newTransform) {

    Field transfromField = FieldUtils.getDeclaredField(TransformTask.class, "transform", true);
    if (null != transfromField) {
        try {//  w w w.j a v  a2  s .  c o m
            transfromField.set(transformTask, newTransform);
        } catch (IllegalAccessException e) {
            throw new GradleException(e.getMessage(), e);
        }
    }
}

From source file:com.tridion.storage.si4t.JPASearchDAOFactory.java

private static void setPrivateField(final Object fieldOwner, final String fieldName, final Object value,
        Logger log) throws IllegalAccessException {
    final Field privateField = getPrivateFieldRec(fieldOwner.getClass(), fieldName, log);

    if (privateField != null) {

        final boolean accessible = privateField.isAccessible();
        privateField.setAccessible(true);

        privateField.set(fieldOwner, value);

        privateField.setAccessible(accessible);
    }//from w  w w.j  av  a  2 s.com
}

From source file:io.tilt.minka.utils.Defaulter.java

/**
 * @param   props the properties instance to look up keys for 
 * @param   configurable //from   www .j  av  a 2 s  .c  om
 *  applying object with pairs of "default" sufixed static fields in the format "some_value_default"
 *  and instance fields in the propercase format without underscores like "someValue" 
 * 
 * @return  TRUE if all defaults were applied. FALSE if some was not !
 */
public static boolean apply(final Properties props, Object configurable) {
    Validate.notNull(props);
    Validate.notNull(configurable);
    boolean all = true;
    for (final Field staticField : getStaticDefaults(configurable.getClass())) {
        final String name = properCaseIt(staticField.getName());
        if (staticField.getName().endsWith(SUFFIX)) {
            final String nameNoDef = name.substring(0, name.length() - SUFFIX.length());
            try {
                final Field instanceField = configurable.getClass().getDeclaredField(nameNoDef);
                try {
                    final PropertyEditor editor = edit(props, configurable, staticField, instanceField);
                    instanceField.setAccessible(true);
                    instanceField.set(configurable, editor.getValue());
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    all = false;
                    logger.error("Defaulter: object <{}> cannot set value for field: {}",
                            configurable.getClass().getSimpleName(), nameNoDef, e);
                }
            } catch (NoSuchFieldException | SecurityException e) {
                all = false;
                logger.error("Defaulter: object <{}> has no field: {} for default static: {} (reason: {})",
                        configurable.getClass().getSimpleName(), nameNoDef, staticField.getName(),
                        e.getClass().getSimpleName());
            }
        }
    }
    return all;
}

From source file:cn.wanghaomiao.seimi.core.SeimiBeanResolver.java

public static <T> T parse(Class<T> target, String text) throws Exception {
    T bean = target.newInstance();/*from w  w w  .  j a va 2 s. c  om*/
    final List<Field> props = new LinkedList<>();
    ReflectionUtils.doWithFields(target, new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            props.add(field);
        }
    });
    JXDocument jxDocument = new JXDocument(text);
    for (Field f : props) {
        Xpath xpathInfo = f.getAnnotation(Xpath.class);
        if (xpathInfo != null) {
            String xpath = xpathInfo.value();
            List<Object> res = jxDocument.sel(xpath);
            boolean accessFlag = f.isAccessible();
            f.setAccessible(true);
            f.set(bean, defaultCastToTargetValue(target, f, res));
            f.setAccessible(accessFlag);
        }
    }
    return bean;
}

From source file:com.iflytek.edu.cloud.frame.utils.ReflectionUtils.java

/**
 * ,private/protected,??setter./*from   ww w  .ja v  a  2  s  .c  o m*/
 */
public static void setFieldValue(final Object object, final String fieldName, final Object value) {
    Field field = getDeclaredField(object, fieldName);

    if (field == null)
        throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + object + "]");

    makeAccessible(field);

    try {
        field.set(object, value);
    } catch (IllegalAccessException e) {
        logger.error("??:{}", e.getMessage());
    }
}

From source file:com.yimidida.shards.utils.ParameterUtil.java

public static Object generatePrimaryKey(Object object, Serializable id) {
    if (object != null) {
        Assert.notNull(id, "generated id can not be null.");

        Class<?> clazz = object.getClass();
        Field[] first = clazz.getDeclaredFields();
        Field[] second = clazz.getSuperclass().getDeclaredFields();

        Field[] fields = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, fields, first.length, second.length);

        for (Field field : fields) {
            field.setAccessible(true);/*from  w w  w . j a  va2 s. c  o  m*/

            PrimaryKey primaryKey = field.getAnnotation(PrimaryKey.class);
            if (primaryKey != null) {
                try {
                    //set id
                    field.set(object, id);

                    return object;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    return null;
}

From source file:com.linkedin.pinot.common.utils.MmapUtils.java

private static void clearSynchronizedMapEntrySetCache() {
    // For some bizarre reason, Collections.synchronizedMap's implementation (at least on JDK 1.8.0.25) caches the
    // entry set, and will thus return stale (and incorrect) values if queried multiple times, as well as cause those
    // entries to not be garbage-collectable. This clears its cache.
    try {/*from   w w  w.j  a  v  a2s.c  o m*/
        Class<?> clazz = BUFFER_TO_CONTEXT_MAP.getClass();
        Field field = clazz.getDeclaredField("entrySet");
        field.setAccessible(true);
        field.set(BUFFER_TO_CONTEXT_MAP, null);
    } catch (Exception e) {
        // Well, that didn't work.
    }
}

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);/*from   ww w.j av a 2 s.co  m*/
    field.set(credentials, value);
}

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

/**
 * This only support updating NON-composite keys.
 *
 * @param <T>//from   w w w .ja  va2  s .  com
 * @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.");
    }
}