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:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void injectClientCloudObject(Object obj, ClientCloudObject cco) {

    for (Field f : obj.getClass().getFields()) {
        if (f.getAnnotation(ClientObject.class) != null) {

            f.setAccessible(true);/*from  w w  w  .j  a v a 2  s. c om*/
            try {
                f.set(obj, cco);
            } catch (Exception e) {
                e.printStackTrace();
                throw new JCloudScaleException(e, "Unexpected error when injecting @ClientCloudObject");
            }

        }
    }

}

From source file:com.jdo.CloudContactUtils.java

public static Object cloneEntity(Object obj) {
    Object obj1 = null;//from   w ww . jav a2  s  .  c  o m
    try {
        obj1 = obj.getClass().newInstance();

        Field f[] = obj.getClass().getDeclaredFields();

        for (Field f1 : f) {

            if (!java.lang.reflect.Modifier.isStatic(f1.getModifiers())) {

                f1.setAccessible(true);

                f1.set(obj1, f1.get(obj));
            }
        }
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return obj1;

}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Set the field represented by the supplied {@link Field field object} on the
 * specified {@link Object target object} to the specified {@code value}.
 * In accordance with {@link Field#set(Object, Object)} semantics, the new value
 * is automatically unwrapped if the underlying field has a primitive type.
 * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
 * @param field the field to set//from   www  .  java  2  s .c  om
 * @param target the target object on which to set the field
 * @param value the value to set; may be {@code null}
 */
public static void setField(Field field, Object target, Object value) {
    try {
        field.set(target, value);
    } catch (IllegalAccessException ex) {
        handleReflectionException(ex);
        throw new IllegalStateException(
                "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
    }
}

From source file:com.dubsar_dictionary.Dubsar.FAQActivity.java

/**
 * Set Proxy for Android 3.2 and below./*from   w  w  w .j a  v  a  2s.  co m*/
 */
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API.");

    HttpHost proxyServer = new HttpHost(host, port);
    // Getting network
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(LOG_TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() });
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(LOG_TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(LOG_TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }

    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:com.igormaznitsa.upom.UPomModel.java

private static void setField(final Object instance, final Field field, final Object value) throws Exception {
    final Object currentValue = field.get(instance);
    if (currentValue == null) {
        if (value != null) {
            field.setAccessible(true);//from   w  ww. ja  va2  s.com
            field.set(instance, value);
        }
    } else if (currentValue instanceof Map) {
        ((Map) currentValue).clear();
        if (value != null) {
            ((Map) currentValue).putAll((Map) value);
        }
    } else if (currentValue instanceof Collection) {
        ((Collection) currentValue).clear();
        if (value != null) {
            ((Collection) currentValue).addAll((Collection) value);
        }
    } else {
        field.set(instance, ensureCloning(value));
    }
}

From source file:com.github.fcannizzaro.resourcer.Resourcer.java

/**
 * Create and BufferedImage and update the field
 *
 * @throws IllegalAccessException/* w ww.j  ava2  s.  co m*/
 */
private static void annotateImage(Field field, com.github.fcannizzaro.resourcer.annotations.Image annotation,
        Object annotated) throws IllegalAccessException {
    try {

        String path = annotation.value();
        boolean pathAbsolute = FileUtils.isPathAbsolute(path);
        String res = getPath(path, IMAGE_DIR);

        if (path.startsWith("http"))
            field.set(annotated, ImageIO.read(new URL(path)));
        else
            field.set(annotated, ImageIO.read(pathAbsolute ? new File(path) : new File(res)));

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:ch.flashcard.HibernateDetachUtility.java

private static void nullOutField(Object value, String fieldName) {
    try {// www  .  ja  v a  2 s .  c om
        Field f = value.getClass().getDeclaredField(fieldName);
        if (f != null) {
            // try to set the field this way
            f.setAccessible(true);
            f.set(value, null);
        }
    } catch (NoSuchFieldException e) {
        // ignore this
    } catch (IllegalAccessException e) {
        // ignore this
    }
}

From source file:com.titilink.camel.rest.util.CommonUtils.java

/**
 * ?// w w w  .j av  a 2  s .c om
 *
 * @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:ch.flashcard.HibernateDetachUtility.java

private static void setField(Object object, String fieldName, Object newValue) {
    try {/*from www .  ja va2 s .co  m*/
        Field f = object.getClass().getDeclaredField(fieldName);
        if (f != null) {
            // try to set the field this way
            f.setAccessible(true);
            f.set(object, newValue);
        }
    } catch (NoSuchFieldException e) {
        // ignore this
    } catch (IllegalAccessException e) {
        // ignore this
    }
}

From source file:net.ostis.sc.memory.SCKeynodesBase.java

private static boolean checkKeynode(SCSession session, SCSegment defaultSegment, Field field)
        throws IllegalArgumentException, IllegalAccessException {
    Keynode annotation = field.getAnnotation(Keynode.class);

    if (annotation != null) {
        String keynodeName = annotation.value();

        if (StringUtils.isEmpty(keynodeName))
            keynodeName = field.getName();

        SCAddr keynode = session.findByIdtf(keynodeName, defaultSegment);
        Validate.notNull(keynode,//from  w ww . j ava  2  s . co  m
                "Not found keynode with URI \"" + defaultSegment.getURI() + "/" + keynodeName + "\"");

        field.set(null, keynode);

        if (log.isDebugEnabled())
            log.debug(defaultSegment.getURI() + "/" + keynodeName + " --> " + field.getName());

        return true;
    } else {
        return false;
    }
}