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.wms.utils.DataUtil.java

public static Object cloneObject(Object obj) {
    try {/* w  w w . j  a v a  2s  .  c  o  m*/
        Object clone = obj.getClass().newInstance();
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            field.set(clone, field.get(obj));
        }
        return clone;
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

public static void traverseAndRecolor(View root, int color, boolean withStates,
        boolean setClickableItemBackgrounds) {
    Context context = root.getContext();

    if (setClickableItemBackgrounds && root.isClickable()) {
        StateListDrawable selectableItemBackground = new StateListDrawable();
        selectableItemBackground.addState(new int[] { android.R.attr.state_pressed },
                new ColorDrawable((color & 0xffffff) | 0x33000000));
        selectableItemBackground.addState(new int[] { android.R.attr.state_focused },
                new ColorDrawable((color & 0xffffff) | 0x44000000));
        selectableItemBackground.addState(new int[] {}, null);
        root.setBackground(selectableItemBackground);
    }/*from ww w. j  av a2s.c o m*/

    if (root instanceof ViewGroup) {
        ViewGroup parent = (ViewGroup) root;
        for (int i = 0; i < parent.getChildCount(); i++) {
            traverseAndRecolor(parent.getChildAt(i), color, withStates, setClickableItemBackgrounds);
        }

    } else if (root instanceof ImageView) {
        ImageView imageView = (ImageView) root;
        Drawable sourceDrawable = imageView.getDrawable();
        if (withStates && sourceDrawable != null && sourceDrawable instanceof BitmapDrawable) {
            imageView.setImageDrawable(
                    makeRecoloredDrawable(context, (BitmapDrawable) sourceDrawable, color, true));
        } else {
            imageView.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
        }

    } else if (root instanceof TextView) {
        TextView textView = (TextView) root;
        if (withStates) {
            int sourceColor = textView.getCurrentTextColor();
            ColorStateList colorStateList = new ColorStateList(
                    new int[][] { new int[] { android.R.attr.state_pressed },
                            new int[] { android.R.attr.state_focused }, new int[] {} },
                    new int[] { sourceColor, sourceColor, color });
            textView.setTextColor(colorStateList);
        } else {
            textView.setTextColor(color);
        }

    } else if (root instanceof AnalogClock) {
        AnalogClock analogClock = (AnalogClock) root;
        try {
            Field hourHandField = AnalogClock.class.getDeclaredField("mHourHand");
            hourHandField.setAccessible(true);
            Field minuteHandField = AnalogClock.class.getDeclaredField("mMinuteHand");
            minuteHandField.setAccessible(true);
            Field dialField = AnalogClock.class.getDeclaredField("mDial");
            dialField.setAccessible(true);
            BitmapDrawable hourHand = (BitmapDrawable) hourHandField.get(analogClock);
            if (hourHand != null) {
                Drawable d = makeRecoloredDrawable(context, hourHand, color, withStates);
                d.setCallback(analogClock);
                hourHandField.set(analogClock, d);
            }
            BitmapDrawable minuteHand = (BitmapDrawable) minuteHandField.get(analogClock);
            if (minuteHand != null) {
                Drawable d = makeRecoloredDrawable(context, minuteHand, color, withStates);
                d.setCallback(analogClock);
                minuteHandField.set(analogClock, d);
            }
            BitmapDrawable dial = (BitmapDrawable) dialField.get(analogClock);
            if (dial != null) {
                Drawable d = makeRecoloredDrawable(context, dial, color, withStates);
                d.setCallback(analogClock);
                dialField.set(analogClock, d);
            }
        } catch (NoSuchFieldException ignored) {
        } catch (IllegalAccessException ignored) {
        } catch (ClassCastException ignored) {
        } // TODO: catch all exceptions?
    }
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.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
 *///ww w  . j  a v a  2s .  c om
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(Field field) throws IllegalArgumentException, IllegalAccessException {
            makeAccessible(field);
            Object srcValue = field.get(src);
            field.set(dest, srcValue);
        }
    }, COPYABLE_FIELDS);
}

From source file:Main.java

public static boolean overrideClassLoader(ClassLoader cl, File dex, File opt) {
    try {//from   ww w .j  a  v  a2  s .  c  o m
        ClassLoader bootstrap = cl.getParent();
        Field fPathList = BaseDexClassLoader.class.getDeclaredField("pathList");
        fPathList.setAccessible(true);
        Object pathList = fPathList.get(cl);
        Class cDexPathList = bootstrap.loadClass("dalvik.system.DexPathList");
        Field fDexElements = cDexPathList.getDeclaredField("dexElements");
        fDexElements.setAccessible(true);
        Object dexElements = fDexElements.get(pathList);
        DexClassLoader cl2 = new DexClassLoader(dex.getAbsolutePath(), opt.getAbsolutePath(), null, bootstrap);
        Object pathList2 = fPathList.get(cl2);
        Object dexElements2 = fDexElements.get(pathList2);
        Object element2 = Array.get(dexElements2, 0);
        int n = Array.getLength(dexElements) + 1;
        Object newDexElements = Array.newInstance(fDexElements.getType().getComponentType(), n);
        Array.set(newDexElements, 0, element2);
        for (int i = 0; i < n - 1; i++) {
            Object element = Array.get(dexElements, i);
            Array.set(newDexElements, i + 1, element);
        }
        fDexElements.set(pathList, newDexElements);
        return true;
    } catch (Exception e) {
        Log.e("lcast", "fail to override classloader " + cl + " with " + dex, e);
        return false;
    }
}

From source file:jp.co.ctc_g.jfw.core.util.Beans.java

private static boolean writePseudoPropertyValueNamed0(String propertyName, Object bean, Object newValue) {
    try {//from  w  ww.  j ava 2 s .  c  o  m
        PropertyDescriptor pd = findPropertyDescriptorFor(bean.getClass(), propertyName);
        // ???????
        if (pd != null) {
            Method writer = pd.getWriteMethod();
            if (writer != null) {
                writer.setAccessible(true);
                writer.invoke(bean, newValue);
                return true;
            } else {
                if (L.isDebugEnabled()) {
                    Map<String, Object> replace = new HashMap<String, Object>(1);
                    replace.put("property", propertyName);
                    L.debug(Strings.substitute(R.getString("D-UTIL#0009"), replace));
                }
                return false;
            }
            // ???????
        } else {
            Field f = bean.getClass().getField(propertyName);
            if (f != null) {
                f.setAccessible(true);
                f.set(bean, newValue);
                return true;
            } else {
                if (L.isDebugEnabled()) {
                    Map<String, Object> replace = new HashMap<String, Object>(1);
                    replace.put("property", propertyName);
                    L.debug(Strings.substitute(R.getString("D-UTIL#0010"), replace));
                }
                return false;
            }
        }
    } catch (SecurityException e) {
        throw new InternalException(Beans.class, "E-UTIL#0010", e);
    } catch (NoSuchFieldException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0011", replace, e);
    } catch (IllegalArgumentException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        throw new InternalException(Beans.class, "E-UTIL#0012", replace, e);
    } catch (IllegalAccessException e) {
        throw new InternalException(Beans.class, "E-UTIL#0013", e);
    } catch (InvocationTargetException e) {
        Map<String, String> replace = new HashMap<String, String>(1);
        replace.put("property", propertyName);
        replace.put("class", bean.getClass().getName());
        throw new InternalException(Beans.class, "E-UTIL#0014", replace, e);
    }
}

From source file:com.smartitengineering.util.bean.BeanFactoryRegistrar.java

private static boolean aggregate(Class<? extends Object> aggregatorClass, Object aggregator)
        throws SecurityException {
    if (aggregatorClass.equals(Object.class)) {
        return true;
    }/*from  w  w w .  ja va2  s .c o m*/
    Class<? extends Object> superClass = aggregatorClass.getSuperclass();
    if (superClass != null) {
        aggregate(superClass, aggregator);
    }
    Aggregator aggregatorAnnotation = aggregatorClass.getAnnotation(Aggregator.class);
    if (aggregatorAnnotation == null || StringUtils.isBlank(aggregatorAnnotation.contextName())) {
        return true;
    }
    BeanFactory beanFactory = getBeanFactorForContext(aggregatorAnnotation.contextName());
    if (beanFactory == null) {
        return true;
    }
    Field[] declaredFields = aggregatorClass.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        InjectableField injectableField = declaredField.getAnnotation(InjectableField.class);
        if (injectableField == null) {
            continue;
        }
        String beanName = StringUtils.isBlank(injectableField.beanName()) && beanFactory.isNameMandatory()
                ? declaredField.getName()
                : injectableField.beanName();
        if (StringUtils.isBlank(beanName) && beanFactory.isNameMandatory()) {
            return true;
        }
        try {
            declaredField.setAccessible(true);
            final Class<?> fieldType = declaredField.getType();
            if (beanFactory.containsBean(beanName, fieldType)) {
                declaredField.set(aggregator, beanFactory.getBean(beanName, fieldType));
            }
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }

    }
    return false;
}

From source file:com.willwinder.universalgcodesender.AbstractControllerTest.java

public static void init()
        throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException, IOException {
    instance = EasyMock.createMockBuilder(AbstractController.class)
            .addMockedMethods("closeCommBeforeEvent", "closeCommAfterEvent", "openCommAfterEvent",
                    "cancelSendBeforeEvent", "cancelSendAfterEvent", "pauseStreamingEvent",
                    "resumeStreamingEvent", "isReadyToSendCommandsEvent", "rawResponseHandler",
                    "statusUpdatesEnabledValueChanged", "statusUpdatesRateValueChanged", "isCommOpen")
            .withConstructor(AbstractCommunicator.class).withArgs(mockCommunicator).createMock();

    // Initialize private variable.
    Field f = AbstractController.class.getDeclaredField("commandCreator");
    f.setAccessible(true);/*w w w.java 2  s  .  c  o  m*/
    f.set(instance, gcodeCreator);

    instance.addListener(mockListener);
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONSerializable deSerialize(Class clz, JSONObject jsonObj)
        throws JSONSerializationException, JSONException {
    Iterator iter = jsonObj.keys();

    if (!JSONSerializable.class.isAssignableFrom(clz)) {
        throw new JSONSerializationException(clz + " is not an instance of " + JSONSerializable.class);
    }//from  w  w  w  .  j a v  a  2  s. c o m

    JSONSerializable retObj;
    try {
        retObj = (JSONSerializable) clz.newInstance();
    } catch (Exception e1) {
        throw new JSONSerializationException(
                "trouble with no-arg instantiation of " + clz.toString() + ": " + e1.getMessage(), e1);
    }

    if (JSONExternalizable.class.isAssignableFrom(clz)) {
        ((JSONExternalizable) retObj).fromJSON(jsonObj);
        return retObj;
    }

    while (iter.hasNext()) {
        String key = (String) iter.next();

        try {
            Field f = clz.getDeclaredField(key);
            if (f != null) {
                f.setAccessible(true);
                Class type = f.getType();

                if (type.isArray()) {
                    JSONArray array = jsonObj.getJSONArray(key);
                    int len = array.length();
                    Class cls = type.getComponentType();

                    Object newArray = Array.newInstance(cls, len);
                    for (int k = 0; k < len; ++k) {
                        loadObject(newArray, cls, k, array);
                    }
                    f.set(retObj, newArray);
                } else {
                    loadObject(retObj, f, jsonObj);
                }
            }
        } catch (Exception e) {
            throw new JSONSerializationException(e.getMessage(), e);
        }
    }

    return retObj;
}

From source file:com.cloud.api.ApiDispatcher.java

public static void plugService(Field field, BaseCmd cmd) {

    Class<?> fc = field.getType();
    Object instance = null;/*from   ww  w.  j  a  v  a2 s  .  c o  m*/

    if (instance == null) {
        throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command "
                + cmd.getClass().getSimpleName());
    }

    try {
        field.setAccessible(true);
        field.set(cmd, instance);
    } catch (IllegalArgumentException e) {
        s_logger.error("IllegalArgumentException at plugService for command " + cmd.getCommandName()
                + ", field " + field.getName());
        throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName()
                + " [Illegal argumet at field " + field.getName() + "]");
    } catch (IllegalAccessException e) {
        s_logger.error("Error at plugService for command " + cmd.getCommandName() + ", field " + field.getName()
                + " is not accessible.");
        throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName()
                + " [field " + field.getName() + " is not accessible]");
    }
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

/**
 * @param entity/*  w  w w .jav  a2s.  c o m*/
 * @param fields
 * @param i
 * @return
 * @throws AutomationFrameworkException
 */
@SuppressWarnings("unchecked")
private static <T> Class<AbstractFeature> processCCFeatureField(T entity, Field field)
        throws AutomationFrameworkException {
    Class<AbstractFeature> clazz;
    try {
        clazz = (Class<AbstractFeature>) field.getType();
    } catch (Exception e) {
        throw new AutomationFrameworkException("Unexpected field type :" + field.getType().getSimpleName()
                + " field name: " + field.getName() + " class: " + entity.getClass().getSimpleName()
                + " Thread ID:" + Thread.currentThread().getId()
                + " \n\tThis field must be of the type that extends AbstractPageObject class.", e);
    }
    try {
        field.set(entity, createFeature(versionControlPreprocessor(clazz)));
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: " + entity.getClass().getSimpleName()
                        + " Thread ID:" + Thread.currentThread().getId(),
                e);
    }
    return clazz;
}