Set Value By Field via reflection - Android java.lang.reflect

Android examples for java.lang.reflect:Field Value

Description

Set Value By Field via reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

import java.text.SimpleDateFormat;

public class Main {
    public static void SetValueByField(Object obj, String fieldName,
            String value) {/*ww w .j  a  va2 s  . co m*/
        Field[] fields = obj.getClass().getFields();
        String fieldType = null;
        if (value == null || "".equals(value.trim())) {
            return;
        }
        try {
            for (Field field : fields) {
                if (field.getName().equalsIgnoreCase(fieldName)) {
                    fieldType = field.getType().getSimpleName();
                    if (fieldType.equals("int")) {
                        field.setInt(obj, Integer.parseInt(value));
                    } else if (fieldType.equals("String")) {
                        field.set(obj, value);
                    } else if (fieldType.equals("float")) {
                        field.setFloat(obj, Float.parseFloat(value));
                    } else if (fieldType.equals("double")) {
                        field.setDouble(obj, Double.parseDouble(value));
                    } else if (fieldType.equals("Date")) {
                        SimpleDateFormat sdf = new SimpleDateFormat(
                                "yyyy-MM-dd HH:mm:ss.SSS");
                        field.set(obj, sdf.parse(value));
                    } else if (fieldType.equals("boolean")) {
                        field.setBoolean(obj, Boolean.parseBoolean(value));
                    } else {
                        throw new Exception("(" + fieldType
                                + ")");
                    }
                }

            }
        } catch (Exception e) {
        }
    }
}

Related Tutorials