Example usage for java.lang.reflect Field get

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public Object get(Object obj) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Returns the value of the field represented by this Field , on the specified object.

Usage

From source file:com.titilink.camel.rest.util.CommonUtils.java

/**
 * requestaction?/*from ww  w .  ja v  a 2  s . co m*/
 *
 * @param instance
 * @param <T>
 * @throws OperationException
 */
private static <T> void checkActionCount(T instance) throws OperationException {
    if (null == instance) {
        LOGGER.error("checkActionCount FAILED! request is null");
        throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
    }

    int actionCount = 0;
    Field[] fields = instance.getClass().getDeclaredFields();
    for (Field field : fields) {
        field.setAccessible(true);
        if (NEED_IGNORE_FIELD.equals(field.getName())) {
            continue;
        }

        try {
            if (null != field.get(instance)) {
                ++actionCount;
            }
        } catch (Exception e) {
            LOGGER.error("checkActionCount exception for req:" + instance, e);
            throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
        }
    }

    if (ACTION_COUNT_ONE != actionCount) {
        LOGGER.error("checkActionCount FAILED! the number of action in request:{} is not " + ACTION_COUNT_ONE,
                instance);
        throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
    }
}

From source file:com.igormaznitsa.upom.UPomModel.java

private static Object getField(final Object instance, final Field field) throws Exception {
    return ensureCloning(field.get(instance));
}

From source file:ReflectionUtils.java

/**
 * ,private/protected,getter.//from   w ww. j  av  a2  s  . com
 */
public static Object getFieldValue(final Object object, final String fieldName) {
    Field field = getDeclaredField(object, fieldName);
    if (field == null)
        throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + object + "]");
    makeAccessible(field);
    Object result = null;
    try {
        result = field.get(object);
    } catch (IllegalAccessException e) {
        logger.error("{}", e);
    }
    return result;
}

From source file:com.xyz.util.ReflectionUtil.java

/**
 * ?,private/protected,??getter.//from  w  w w  . j a va 2s .  c o m
 */
public static Object getFieldValue(final Object object, final String fieldName) {
    Field field = getDeclaredField(object, fieldName);

    if (field == null)
        throw new IllegalArgumentException(
                "Could not find field [" + fieldName + "] on target [" + object + "]");

    makeAccessible(field);

    Object result = null;
    try {
        result = field.get(object);
    } catch (IllegalAccessException e) {
        logger.error("??" + e.getMessage());
    }
    return result;
}

From source file:com.joyent.manta.client.MantaObjectOutputStream.java

/**
 * Uses reflection to look into the specified {@link OutputStream} instance to
 * see if there is a boolean field set called "closed", if it is set and accessible
 * via reflection, we return its value. Otherwise, we return null.
 *
 * @param stream instance to reflect on for closed property
 * @return reference to closed property or null if unavailable
 *///  w  w w.  j ava2  s .c o m
protected static Boolean isInnerStreamClosed(final OutputStream stream) {
    OutputStream inner = findMostInnerOutputStream(stream);

    // If the inner most stream is a closed instance, then we can assume
    // the stream is close.
    if (inner.getClass().equals(ClosedOutputStream.class)) {
        return true;
    }

    try {
        Field f = FieldUtils.getField(inner.getClass(), "closed", true);

        if (f == null) {
            throw new IllegalArgumentException("FieldUtils.getField(inner.getClass()) " + "returned null");
        }

        Object result = f.get(inner);
        return (boolean) result;
    } catch (IllegalArgumentException | IllegalAccessException | ClassCastException e) {
        String msg = String.format("Error finding [closed] field on class: %s", inner.getClass());
        LOGGER.warn(msg, e);
        /* If we don't have an inner field called closed, it is inaccessible or
         * the field isn't a boolean, return null because we are now dealing with
         * undefined behavior. */
        return null;
    }
}

From source file:com.netflix.astyanax.thrift.ThriftUtils.java

/**
 * Quick and dirty implementation that converts thrift DDL to a Properties object by flattening
 * the parameters/*from w  w  w. j  a  v  a 2s. c o  m*/
 * @param prefix
 * @param properties
 * @param entity
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void setPropertiesFromThrift(String prefix, Properties properties, org.apache.thrift.TBase entity)
        throws Exception {
    Field field = entity.getClass().getDeclaredField("metaDataMap");
    Map<org.apache.thrift.TFieldIdEnum, org.apache.thrift.meta_data.FieldMetaData> fields = (Map<org.apache.thrift.TFieldIdEnum, FieldMetaData>) field
            .get(entity);

    for (Entry<org.apache.thrift.TFieldIdEnum, FieldMetaData> f : fields.entrySet()) {
        ThriftTypes type = ThriftTypes.values()[f.getValue().valueMetaData.type];
        Object value = entity.getFieldValue(f.getKey());
        if (value == null)
            continue;

        switch (type) {
        case VOID:
            break;
        case BOOL:
        case BYTE:
        case DOUBLE:
        case I16:
        case I32:
        case I64:
        case STRING:
        case ENUM:
            if (value instanceof byte[]) {
                properties.put(prefix + f.getKey().getFieldName(), Base64.encodeBase64String((byte[]) value));
            } else if (value instanceof ByteBuffer) {
                properties.put(prefix + f.getKey().getFieldName(), base64Encode((ByteBuffer) value));
            } else {
                properties.put(prefix + f.getKey().getFieldName(), value.toString());
            }
            break;
        case MAP: {
            String newPrefix = prefix + f.getKey().getFieldName() + ".";
            org.apache.thrift.meta_data.MapMetaData meta = (org.apache.thrift.meta_data.MapMetaData) f
                    .getValue().valueMetaData;
            if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                Map<Object, Object> map = (Map<Object, Object>) value;
                for (Entry<Object, Object> entry : map.entrySet()) {
                    properties.put(newPrefix + entry.getKey(), entry.getValue().toString());
                }
            } else {
                LOG.error(String.format("Unable to serializer field '%s' key type '%s' not supported",
                        f.getKey().getFieldName(), meta.keyMetaData.getTypedefName()));
            }
            break;
        }
        case LIST: {
            String newPrefix = prefix + f.getKey().getFieldName() + ".";

            List<Object> list = (List<Object>) value;
            org.apache.thrift.meta_data.ListMetaData listMeta = (org.apache.thrift.meta_data.ListMetaData) f
                    .getValue().valueMetaData;
            for (Object entry : list) {
                String id;
                if (entry instanceof CfDef) {
                    id = ((CfDef) entry).name;
                } else if (entry instanceof ColumnDef) {
                    ByteBuffer name = ((ColumnDef) entry).name;
                    id = base64Encode(name);
                } else {
                    LOG.error("Don't know how to convert to properties "
                            + listMeta.elemMetaData.getTypedefName());
                    continue;
                }

                if (listMeta.elemMetaData.isStruct()) {
                    setPropertiesFromThrift(newPrefix + id + ".", properties, (org.apache.thrift.TBase) entry);
                } else {
                    properties.put(newPrefix + id, entry);
                }
            }

            break;
        }
        case STRUCT: {
            setPropertiesFromThrift(prefix + f.getKey().getFieldName() + ".", properties,
                    (org.apache.thrift.TBase) value);
            break;
        }
        case SET:
        default:
            LOG.error("Unhandled value : " + f.getKey().getFieldName() + " " + type);
            break;
        }
    }
}

From source file:net.sf.eclipsecs.core.builder.CheckerFactory.java

private static void applyTreeWalkerCacheWorkaround(Checker checker) {
    try {/*w  w  w.j a  v a  2  s  . co m*/
        Field fileSetChecksField = Checker.class.getDeclaredField("mFileSetChecks");
        fileSetChecksField.setAccessible(true);

        @SuppressWarnings("unchecked")
        List<FileSetCheck> fileSetChecks = (List<FileSetCheck>) fileSetChecksField.get(checker);

        for (FileSetCheck fsc : fileSetChecks) {
            if (fsc instanceof TreeWalker) {
                TreeWalker tw = (TreeWalker) fsc;

                // only reset when we have a "default cache" without an actual configured cache file.
                Field cacheField = TreeWalker.class.getDeclaredField("mCache");
                cacheField.setAccessible(true);

                Object cache = cacheField.get(tw);

                Field detailsFileField = cache.getClass().getDeclaredField("mDetailsFile");
                detailsFileField.setAccessible(true);

                if (detailsFileField.get(cache) == null) {
                    tw.setCacheFile(null);
                }
            }
        }
    } catch (Exception e) {
        // Ah, what the heck, I tried. Now get out of my way.
    }
}

From source file:com.netflix.astyanax.thrift.ThriftUtils.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object populateObject(Object obj, Map<String, Object> map) throws Exception {
    org.apache.thrift.TBase entity = (org.apache.thrift.TBase) obj;
    Field field = entity.getClass().getDeclaredField("metaDataMap");
    Map<org.apache.thrift.TFieldIdEnum, org.apache.thrift.meta_data.FieldMetaData> fields = (Map<org.apache.thrift.TFieldIdEnum, FieldMetaData>) field
            .get(entity);//from w  ww .  j av  a 2s  .  c  o  m

    for (Entry<TFieldIdEnum, FieldMetaData> f : fields.entrySet()) {
        Object value = map.get(f.getKey().getFieldName());
        if (value != null) {
            ThriftTypes type = ThriftTypes.values()[f.getValue().valueMetaData.type];

            switch (type) {
            case VOID:
                break;
            case BYTE:
            case BOOL:
            case DOUBLE:
            case I16:
            case I32:
            case I64:
            case STRING:
                try {
                    entity.setFieldValue(f.getKey(), valueForBasicType(value, f.getValue().valueMetaData.type));
                } catch (ClassCastException e) {
                    if (e.getMessage().contains(ByteBuffer.class.getCanonicalName())) {
                        entity.setFieldValue(f.getKey(), ByteBuffer.wrap(Base64.decodeBase64((String) value)));
                    } else {
                        throw e;
                    }
                }
                break;
            case ENUM: {
                org.apache.thrift.meta_data.EnumMetaData meta = (org.apache.thrift.meta_data.EnumMetaData) f
                        .getValue().valueMetaData;
                Object e = meta.enumClass;
                entity.setFieldValue(f.getKey(), Enum.valueOf((Class<Enum>) e, (String) value));
                break;
            }
            case MAP: {
                org.apache.thrift.meta_data.MapMetaData meta = (org.apache.thrift.meta_data.MapMetaData) f
                        .getValue().valueMetaData;
                if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                    Map<Object, Object> childMap = (Map<Object, Object>) value;
                    Map<Object, Object> childEntityMap = Maps.newHashMap();
                    entity.setFieldValue(f.getKey(), childEntityMap);

                    if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                        for (Entry<Object, Object> entry : childMap.entrySet()) {
                            Object childKey = valueForBasicType(entry.getKey(), meta.keyMetaData.type);
                            Object childValue = valueForBasicType(entry.getValue(), meta.valueMetaData.type);
                            childEntityMap.put(childKey, childValue);
                        }
                    }
                } else {
                    LOG.error(String.format("Unable to serializer field '%s' key type '%s' not supported",
                            f.getKey().getFieldName(), meta.keyMetaData.getTypedefName()));
                }
                break;
            }
            case LIST: {
                Map<String, Object> childMap = (Map<String, Object>) value;
                org.apache.thrift.meta_data.ListMetaData listMeta = (org.apache.thrift.meta_data.ListMetaData) f
                        .getValue().valueMetaData;

                // Create an empty list and attach to the parent entity
                List<Object> childList = Lists.newArrayList();
                entity.setFieldValue(f.getKey(), childList);

                if (listMeta.elemMetaData instanceof org.apache.thrift.meta_data.StructMetaData) {
                    org.apache.thrift.meta_data.StructMetaData structMeta = (org.apache.thrift.meta_data.StructMetaData) listMeta.elemMetaData;
                    for (Entry<String, Object> childElement : childMap.entrySet()) {
                        org.apache.thrift.TBase childEntity = structMeta.structClass.newInstance();
                        populateObject(childEntity, (Map<String, Object>) childElement.getValue());
                        childList.add(childEntity);
                    }
                }
                break;
            }
            case STRUCT: {
                break;
            }
            case SET:
            default:
                LOG.error("Unhandled value : " + f.getKey().getFieldName() + " " + type);
                break;
            }
        }
    }
    return entity;
}

From source file:com.titilink.camel.rest.util.CommonUtils.java

/**
 * ?//from   w w  w  . j  a v a2 s .c o  m
 *
 * @param instance
 * @param <T>
 * @throws OperationException
 */
private static <T> void trimAndCheckParameter(T instance) throws OperationException {
    if (null == instance) {
        return;
    }

    if ((!instance.getClass().getName().startsWith(PACKAGE_NAME_PREFIX)) && instance.getClass() != List.class) {
        return;
    }

    Field[] fields = instance.getClass().getDeclaredFields();
    String value = null;
    for (Field field : fields) {
        field.setAccessible(true);

        try {
            if (field.getType().getName().startsWith(PACKAGE_NAME_PREFIX)) {
                trimAndCheckParameter(field.get(instance));
            } else if (field.getType() == String.class) {
                value = (String) field.get(instance);
                if (null != value) {
                    field.set(instance, value.trim());
                }
            } else if (field.getType() == List.class) {
                List<T> list = (List<T>) field.get(instance);
                if (null != list) {
                    for (T t : list) {
                        trimAndCheckParameter(t);
                    }
                }
            }
        } catch (OperationException e) {
            LOGGER.error("trimAndCheckParameter method error, trim exception field={}, instance={}", field,
                    instance);

            LOGGER.error("trimAndCheckParameter method error, trim exception e=", e);
            throw new OperationException(Status.CLIENT_ERROR_BAD_REQUEST.getCode(), e.getErrorCode(),
                    e.getMessage());
        } catch (Exception e) {
            LOGGER.error("trimAndCheckParameter method error, trim exception field={}, instance={}", field,
                    instance);
            LOGGER.error("trimAndCheckParameter method error, trim exception e=", e);
            throw new OperationException(CommonCode.INVALID_INPUT_PARAMETER, "Invalid input params");
        }
    }

    // ??
    checkParameter(instance);
}

From source file:com.kcs.core.utilities.Utility.java

public static void analyze(final Object obj) {
    ReflectionUtils.doWithFields(obj.getClass(), new ReflectionUtils.FieldCallback() {
        @Override//from   w ww.  j a v  a2 s  .c  om
        public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException {
            field.setAccessible(true);
            logger.debug(field.getName() + " : " + field.get(obj));
        }
    });
}