Java Reflection Field Set setFieldValeByType(Field field, Object obj, String value)

Here you can find the source of setFieldValeByType(Field field, Object obj, String value)

Description

set Field Vale By Type

License

Apache License

Declaration

public static void setFieldValeByType(Field field, Object obj, String value) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

public class Main {

    public static void setFieldValeByType(Field field, Object obj, String value) throws Exception {

        Class<?> type = field.getType();

        String typeName = type.getName();

        if (typeName.equals("int")) {

            if (value.equals("")) {
                value = "0";
            }//from   w ww .j  av  a 2  s .  c  om
            field.set(obj, Integer.valueOf(value));

        } else if (typeName.equals("long")) {

            if (value.equals("")) {
                value = "0";
            }
            field.set(obj, Long.valueOf(value));

        } else if (typeName.equals("boolean")) {

            if (value.equals("")) {
                value = "false";
            }
            field.set(obj, Boolean.valueOf(value));

        } else if (typeName.equals("double")) {

            if (value.equals("")) {
                value = "0.0";
            }
            field.set(obj, Double.valueOf(value));

        } else {

            field.set(obj, value);
        }
    }
}

Related

  1. setFieldPrimitive(Object target, Field field, Object value)
  2. setFields(Field field, Object value, Object config)
  3. setFields(final Map fields, final Object target)
  4. setFieldStatic(final Object pBean, final String fieldname, final Object pInject)
  5. setFieldVal(Object object, String name, Object val)
  6. setFieldViaReflection(String fieldName, V value, T classInstance)
  7. setFieldVisible( Class classToModify, String fieldName)
  8. setFieldWithReflection(Object object, String fieldName, Object fieldValue)