set Object Field Value - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

set Object Field Value

Demo Code


//package com.java2s;

import java.lang.reflect.Method;
import android.text.TextUtils;
import android.util.Log;

public class Main {
    private static final String CLASS = "ReflectionUtil";
    private static final String METHOD_HEAD_SET = "set";

    public static void setObjectFieldVal(Object object, String fieldName,
            Object value) {/*  w w w  .  j  a  v  a 2 s.c o  m*/
        if (object == null || TextUtils.isEmpty(fieldName))
            return;

        Method method = reflectClassMethod(object.getClass(),
                METHOD_HEAD_SET + fieldName, true);
        if (method == null)
            return;

        try {
            method.invoke(object, value);
        } catch (Exception e) {
            Log.e(CLASS, e.getMessage() + "");
        }
    }

    private static Method reflectClassMethod(Class<?> clazz,
            String methodName, boolean isEqualsIgnoreCase) {
        if (clazz == null || TextUtils.isEmpty(methodName))
            return null;

        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if ((isEqualsIgnoreCase && method.getName().equalsIgnoreCase(
                    methodName))
                    || method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }
}

Related Tutorials