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.autobizlogic.abl.util.BeanUtil.java

protected static void setValueWithField(Field field, Object bean, Object value) {

    try {//from w w w.jav a2  s  .  c  o m
        field.setAccessible(true);
        field.set(bean, value);
    } catch (Exception ex) {
        String extraInfo = "";
        if (value != null) {
            // If the two classes have the same name, it's probably a classloader problem,
            // so we generate more informative output to help debug
            if (field.getType().getName().equals(value.getClass().getName())) {
                extraInfo = ". It looks like the two classes have the same name, so this is "
                        + "probably a classloader issue. The bean field's class comes from "
                        + field.getType().getClassLoader() + ", the bean itself comes from "
                        + bean.getClass().getClassLoader() + ", the value class comes from "
                        + value.getClass().getClassLoader();
            }
        }
        throw new RuntimeException("Unable to set property " + field.getName() + " on instance of "
                + bean.getClass().getName() + " using field " + field.getName() + extraInfo, ex);
    }
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static Message convertJSONObjectToMessage(JSONObject jo, Class c, Registry<Class> r) {
    //System.out.println("JSON.convertJSONObjectToMessage: " + jo.toJSONString());
    try {//from  w w w .  j  a v a2 s .  c o  m
        Message result = (Message) c.newInstance();
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, jo, f, r);
            Object lookup = jo.get(f.getName());
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }
        return result;
    } catch (Exception ex) {
        //ex.printStackTrace();
        return null;
    }
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

public static void setField(Object obj, String fieldName, Object value)
        throws NoSuchFieldException, IllegalArgumentException {
    Class<?> clazz = obj.getClass();

    Field field = clazz.getDeclaredField(fieldName);
    field.setAccessible(true);/*from  w  ww . ja v  a 2 s . co m*/

    try {
        field.set(obj, value);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

From source file:com.greenline.hrs.admin.cache.redis.util.RedisInfoParser.java

/**
 * RedisInfoMapT?RedisInfoMapRedis?/*from w  w  w .  ja  v a  2  s  . c o  m*/
 * RedisServerInfoPO
 *
 * @param instanceType class
 * @param redisInfoMap Map
 * @param <T>          
 * @return instanceTypeinfomapnullinfoMap?instancenullRedisServerInfoPO
 */
public static <T> T parserRedisInfo(Class<T> instanceType, Map<String, String> redisInfoMap) {
    if (instanceType == null || redisInfoMap == null || redisInfoMap.isEmpty()) {
        return null;
    }
    T instance = null;
    try {
        instance = instanceType.newInstance();
    } catch (Exception e) {
        LOG.error("Instance:" + instanceType.getName(), e);
        return null;
    }
    Field[] fields = instanceType.getDeclaredFields();
    String inputName = null;
    for (Field field : fields) {
        ParserField parserField = field.getAnnotation(ParserField.class);
        if (parserField != null) {
            inputName = parserField.inputName();
        } else {
            inputName = field.getName();
        }
        if (redisInfoMap.containsKey(inputName)) {
            field.setAccessible(true);
            try {
                field.set(instance, ConvertUtils.convert(redisInfoMap.get(inputName), field.getType()));
            } catch (Exception e) {
                LOG.error("Field:" + field.getName() + "\t|\t value:" + redisInfoMap.get(inputName), e);
            }
        }
    }
    return instance;
}

From source file:info.donsun.core.utils.Reflections.java

/**
 * , private/protected, ??setter./*from   ww  w.j a  v  a 2  s.co  m*/
 */
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

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

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

From source file:com.cxypub.baseframework.sdk.util.ReflectionUtils.java

/**
 * , private/protected, ??setter./*from  ww w.  j a  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.ghy.common.util.reflection.ReflectionUtils.java

/**
 * , private/protected, ??setter.//from   w ww. j ava 2s.  co m
 */
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
    Field field = getAccessibleField(obj, fieldName);

    if (field == null) {
        throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
    }
    System.out.println("-----field-----" + field.getType());
    try {
        field.set(obj, value);
    } catch (IllegalAccessException e) {
        logger.error("??:{}", e.getMessage());
    }
}

From source file:Main.java

public static <C> C cloneObject(C original) {
    try {//from  www.j  a va  2 s.  c o  m
        C clone = (C) original.getClass().newInstance();
        for (Field field : getAllFieldsValues(original.getClass())) {
            field.setAccessible(true);
            if (field.get(original) == null || Modifier.isFinal(field.getModifiers())) {
                continue;
            }
            if (field.getType().isPrimitive() || field.getType().equals(String.class)
                    || field.getType().getSuperclass().equals(Number.class)
                    || field.getType().equals(Boolean.class)) {
                field.set(clone, field.get(original));
            } else {
                Object childObj = field.get(original);
                if (childObj == original) {
                    field.set(clone, clone);
                } else {
                    field.set(clone, cloneObject(field.get(original)));
                }
            }
        }
        return clone;
    } catch (Exception e) {
        return null;
    }
}

From source file:de.erdesignerng.visual.Java3DUtils.java

private static void addLibraryPath(String pathToAdd) throws Exception {
    Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
    usrPathsField.setAccessible(true);/* w ww .j av a  2 s . co m*/

    //get array of paths
    String[] paths = (String[]) usrPathsField.get(null);

    //check if the path to add is already present
    for (String path : paths) {
        if (path.equals(pathToAdd)) {
            return;
        }
    }

    //add the new path
    String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
    newPaths[newPaths.length - 1] = pathToAdd;
    usrPathsField.set(null, newPaths);
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Hack to disable crypto restrictions until Java 9 is out.
 *
 * See http://stackoverflow.com/a/22492582/2672392
 *///  w ww  .ja v  a 2s.  co m
public static void removeRestrictions() {
    try {
        Class<?> jceSecurityClass = Class.forName("javax.crypto.JceSecurity");
        Class<?> cryptoPermissionsClass = Class.forName("javax.crypto.CryptoPermissions");
        Class<?> cryptoAllPermissionClass = Class.forName("javax.crypto.CryptoAllPermission");

        Field isRestrictedField = jceSecurityClass.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        Field defaultPolicyField = jceSecurityClass.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        Field permsField = cryptoPermissionsClass.getDeclaredField("perms");
        permsField.setAccessible(true);
        ((Map<?, ?>) permsField.get(defaultPolicy)).clear();

        Field cryptoAllPermissionInstanceField = cryptoAllPermissionClass.getDeclaredField("INSTANCE");
        cryptoAllPermissionInstanceField.setAccessible(true);
        defaultPolicy.add((Permission) cryptoAllPermissionInstanceField.get(null));
    } catch (Exception e) {
        // ignore
    }
}