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: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 w ww .  j av a 2  s.  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);
}

From source file:com.splicemachine.orc.OrcTester.java

private static void setFieldValue(Object instance, String name, Object value) {
    try {/*  ww  w .j  ava  2s.  co  m*/
        Field writerField = instance.getClass().getDeclaredField(name);
        writerField.setAccessible(true);
        writerField.set(instance, value);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Given the source object and the destination, which must be the same class
 * or a subclass, copy all fields, including inherited fields. Designed to
 * work on objects with public no-arg constructors.
 * //from  ww  w  .  j  a va 2s.com
 * @throws IllegalArgumentException if the arguments are incompatible
 */
public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException {
    if (src == null) {
        throw new IllegalArgumentException("Source for field copy cannot be null");
    }
    if (dest == null) {
        throw new IllegalArgumentException("Destination for field copy cannot be null");
    }
    if (!src.getClass().isAssignableFrom(dest.getClass())) {
        throw new IllegalArgumentException("Destination class [" + dest.getClass().getName()
                + "] must be same or subclass as source class [" + src.getClass().getName() + "]");
    }
    doWithFields(src.getClass(), new FieldCallback() {
        public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
            makeAccessible(field);
            final Object srcValue = field.get(src);
            field.set(dest, srcValue);
        }
    }, COPYABLE_FIELDS);
}

From source file:be.fedict.commons.eid.consumer.tlv.TlvParser.java

private static <T> T parseThrowing(final byte[] file, final Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    final Field[] fields = tlvClass.getDeclaredFields();
    final Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    final T tlvObject = tlvClass.newInstance();
    for (Field field : fields) {
        final TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null != tlvFieldAnnotation) {
            final int tagId = tlvFieldAnnotation.value();
            if (tlvFields.containsKey(new Integer(tagId))) {
                throw new IllegalArgumentException("TLV field duplicate: " + tagId);
            }/*from  w w w. j  av a  2s.c  om*/
            tlvFields.put(new Integer(tagId), field);
        }
        final OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class);
        if (null != originalDataAnnotation) {
            field.setAccessible(true);
            field.set(tlvObject, file);
        }
    }

    int idx = 0;
    while (idx < file.length - 1) {
        final byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            final Field tlvField = tlvFields.get(new Integer(tag));
            final Class<?> tlvType = tlvField.getType();
            final ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            final byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                final Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                final DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

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

public static void escapeHTMLString(Object escapeObject) {
    String oldData = "";
    String newData = "";
    try {/*  ww  w  .  j a  v  a2 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:io.tempra.AppServer.java

/**
 * Adds the specified path to the java library path
 *
 * @param pathToAdd//from www  .j  a  v  a  2s.  c  o  m
 *            the path to add
 * @throws Exception
 */
public static void addLibraryPath(String pathToAdd) throws Exception {
    final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
    usrPathsField.setAccessible(true);

    // get array of paths
    final 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
    final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
    newPaths[newPaths.length - 1] = pathToAdd;
    usrPathsField.set(null, newPaths);
}

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

public static void trimString(Object obj, boolean isLower) {
    String oldData = "";
    String newData = "";
    try {/* www . j ava2  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:com.comphenix.noxp.FieldUtils.java

/**
 * Write a field.//  w  w w . ja v  a2  s .  co m
 * 
 * @param field to write
 * @param target the object to call on, may be null for static fields
 * @param value to set
 * @param forceAccess whether to break scope restrictions using the
 *            <code>setAccessible</code> method. <code>False</code> will
 *            only match public fields.
 * @throws IllegalArgumentException if the field is null
 * @throws IllegalAccessException if the field is not made accessible or is
 *             final
 */
public static void writeField(Field field, Object target, Object value, boolean forceAccess)
        throws IllegalAccessException {
    if (field == null) {
        throw new IllegalArgumentException("The field must not be null");
    }
    if (forceAccess && !field.isAccessible()) {
        field.setAccessible(true);
    } else {
        MemberUtils.setAccessibleWorkaround(field);
    }
    field.set(target, value);
}

From source file:com.dianping.resource.io.util.ReflectionUtils.java

/**
 * Given the source object and the destination, which must be the same class
 * or a subclass, copy all fields, including inherited fields. Designed to
 * work on objects with public no-arg constructors.
 * @throws IllegalArgumentException if the arguments are incompatible
 *///from   w ww.  j  av  a  2 s. com
public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException {
    if (src == null) {
        throw new IllegalArgumentException("Source for field copy cannot be null");
    }
    if (dest == null) {
        throw new IllegalArgumentException("Destination for field copy cannot be null");
    }
    if (!src.getClass().isAssignableFrom(dest.getClass())) {
        throw new IllegalArgumentException("Destination class [" + dest.getClass().getName()
                + "] must be same or subclass as source class [" + src.getClass().getName() + "]");
    }
    doWithFields(src.getClass(), new FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            makeAccessible(field);
            Object srcValue = field.get(src);
            field.set(dest, srcValue);
        }
    }, COPYABLE_FIELDS);
}

From source file:com.spotify.helios.client.DefaultHttpConnector.java

private static void setRequestMethod(final HttpURLConnection connection, final String method,
        final boolean isHttps) {
    // Nasty workaround for ancient HttpURLConnection only supporting few methods
    final Class<?> httpURLConnectionClass = connection.getClass();
    try {//from   w ww  .jav a2 s . c o  m
        Field methodField;
        HttpURLConnection delegate;
        if (isHttps) {
            final Field delegateField = httpURLConnectionClass.getDeclaredField("delegate");
            delegateField.setAccessible(true);
            delegate = (HttpURLConnection) delegateField.get(connection);
            methodField = delegate.getClass().getSuperclass().getSuperclass().getSuperclass()
                    .getDeclaredField("method");
        } else {
            delegate = connection;
            methodField = httpURLConnectionClass.getSuperclass().getDeclaredField("method");
        }

        methodField.setAccessible(true);
        methodField.set(delegate, method);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw Throwables.propagate(e);
    }
}