Example usage for java.lang.reflect Field setAccessible

List of usage examples for java.lang.reflect Field setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:Main.java

public static Object getFieldValue(Object object, String fieldName) {
    try {//from   w  ww  . j  av  a2 s  .  c o m
        final Field field = getField(object.getClass(), fieldName);
        if (field == null) {
            throw new IllegalArgumentException("No field '" + fieldName + "' found in "
                    + object.getClass().getName() + " or its super classes");
        }
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        return field.get(object);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public Map<Field, Column> buildEntityFieldColumnMap(Class<? extends DalEntity> entityClass) {
    Map<Field, Column> columnByField = new LinkedHashMap<Field, Column>();

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            fld.setAccessible(true);
            columnByField.put(fld, column);
        }//from  w w w .  j av  a  2  s .c om
    }

    return columnByField;
}

From source file:com.fengduo.bee.commons.core.lang.BeanUtils.java

private static Unsafe getUnsafe() throws Exception {
    Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
    theUnsafe.setAccessible(true);
    return (Unsafe) theUnsafe.get(null);
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static Object getValueAccroudBean(Object bean, String field, Object value) {
    Class<?> clazz = bean.getClass();
    try {//from   www.ja v  a  2  s .co  m
        Field f = getDeclaredField(clazz, NamingUtil.dbNameToJavaName(field));
        f.setAccessible(true);
        try {
            return TypeConvertUtil.convert(f.getType(), value);
        } catch (IllegalArgumentException e) {
            throw new UnknowException(e);
        }
    } catch (SecurityException e) {
        throw new UnknowException(e);
    } catch (NoSuchFieldException e) {
        throw new JavaFieldNotFoundException(clazz, field);
    }
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static void setValueToBean(Object bean, String field, Object value) {
    Class<?> clazz = bean.getClass();
    try {/*from w ww  .  ja  v a2 s.  c  om*/
        Field f = getDeclaredField(clazz, NamingUtil.dbNameToJavaName(field));
        f.setAccessible(true);
        try {
            f.set(bean, TypeConvertUtil.convert(f.getType(), value));
        } catch (IllegalArgumentException e) {
            throw new UnknowException(e);
        } catch (IllegalAccessException e) {
            throw new UnknowException(e);
        }
    } catch (SecurityException e) {
        throw new UnknowException(e);
    } catch (NoSuchFieldException e) {
        throw new JavaFieldNotFoundException(clazz, field);
    }
}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static Object getValueFromBean(Object bean, String field) {
    Class<?> clazz = bean.getClass();
    try {/*w  w w  .j  a v a2s  .  c  o m*/
        Field f = getDeclaredField(clazz, NamingUtil.dbNameToJavaName(field));
        f.setAccessible(true);
        try {
            return f.get(bean);
        } catch (IllegalArgumentException e) {
            throw new UnknowException(e);
        } catch (IllegalAccessException e) {
            throw new UnknowException(e);
        }
    } catch (SecurityException e) {
        throw new UnknowException(e);
    } catch (NoSuchFieldException e) {
        throw new JavaFieldNotFoundException(clazz, field);
    }
}

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   ww  w .ja 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.ms.commons.test.common.ReflectUtil.java

public static boolean isValueEqualsBean(Object bean, String field, Object value) {
    Class<?> clazz = bean.getClass();
    try {/*from  ww w.  ja v a  2s  . c  o m*/
        Field f = getDeclaredField(clazz, NamingUtil.dbNameToJavaName(field));
        f.setAccessible(true);
        try {
            Object beanValue = f.get(bean);
            Object fieldValue = TypeConvertUtil.convert(f.getType(), value);
            return CompareUtil.isObjectEquals(beanValue, fieldValue);
        } catch (IllegalArgumentException e) {
            throw new UnknowException(e);
        } catch (IllegalAccessException e) {
            throw new UnknowException(e);
        }
    } catch (SecurityException e) {
        throw new UnknowException(e);
    } catch (NoSuchFieldException e) {
        throw new JavaFieldNotFoundException(clazz, field);
    }
}

From source file:de.cbb.mplayer.mapping.MappingUtil.java

private static void mapFieldToEntity(Field field, Object presenter, Object entity) {
    try {/* w  w w . j a  va2s. c  om*/
        if (!Control.class.isAssignableFrom(field.getType()))
            return;
    } catch (Exception ex) {
        log.debug("mapFieldToEntity failed", ex);
    }
    try {
        String fieldname = field.getName();
        field.setAccessible(true);
        Object value1 = null;

        ValueWrapper wrapper = MappingFactory.buildValueWrapper(presenter, field, value1, entity, fieldname);
        if (wrapper == null)
            return;
        value1 = wrapper.getValue();

        PropertyUtils.setSimpleProperty(entity, fieldname, value1);
    } catch (Exception ex) {
        log.debug("Unmapped control: " + field.getName() + " [" + ex.toString() + "]");
    }
}

From source file:io.tilt.minka.utils.Defaulter.java

/**
 * @param   props the properties instance to look up keys for 
 * @param   configurable /* ww w  . j  a va2  s .c om*/
 *  applying object with pairs of "default" sufixed static fields in the format "some_value_default"
 *  and instance fields in the propercase format without underscores like "someValue" 
 * 
 * @return  TRUE if all defaults were applied. FALSE if some was not !
 */
public static boolean apply(final Properties props, Object configurable) {
    Validate.notNull(props);
    Validate.notNull(configurable);
    boolean all = true;
    for (final Field staticField : getStaticDefaults(configurable.getClass())) {
        final String name = properCaseIt(staticField.getName());
        if (staticField.getName().endsWith(SUFFIX)) {
            final String nameNoDef = name.substring(0, name.length() - SUFFIX.length());
            try {
                final Field instanceField = configurable.getClass().getDeclaredField(nameNoDef);
                try {
                    final PropertyEditor editor = edit(props, configurable, staticField, instanceField);
                    instanceField.setAccessible(true);
                    instanceField.set(configurable, editor.getValue());
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    all = false;
                    logger.error("Defaulter: object <{}> cannot set value for field: {}",
                            configurable.getClass().getSimpleName(), nameNoDef, e);
                }
            } catch (NoSuchFieldException | SecurityException e) {
                all = false;
                logger.error("Defaulter: object <{}> has no field: {} for default static: {} (reason: {})",
                        configurable.getClass().getSimpleName(), nameNoDef, staticField.getName(),
                        e.getClass().getSimpleName());
            }
        }
    }
    return all;
}