Example usage for java.lang.reflect Field getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the field represented by this Field object.

Usage

From source file:com.greenline.hrs.admin.cache.redis.util.RedisInfoParser.java

/**
 * RedisInfoMapT?RedisInfoMapRedis?/*from  ww w .java2s  .co m*/
 * RedisServerInfoPO
 *
 * @param instanceType class
 * @param redisInfoMap Map
 * @param <T>          
 * @return instanceTypeinfomapnullinfoMap?instancenullRedisServerInfoPO
 */
public static <T> T parserRedisInfo(Class<T> instanceType, Map<String, String> redisInfoMap) {
    if (instanceType == null || redisInfoMap == null || redisInfoMap.isEmpty()) {
        return null;
    }
    T instance = null;
    try {
        instance = instanceType.newInstance();
    } catch (Exception e) {
        LOG.error("Instance:" + instanceType.getName(), e);
        return null;
    }
    Field[] fields = instanceType.getDeclaredFields();
    String inputName = null;
    for (Field field : fields) {
        ParserField parserField = field.getAnnotation(ParserField.class);
        if (parserField != null) {
            inputName = parserField.inputName();
        } else {
            inputName = field.getName();
        }
        if (redisInfoMap.containsKey(inputName)) {
            field.setAccessible(true);
            try {
                field.set(instance, ConvertUtils.convert(redisInfoMap.get(inputName), field.getType()));
            } catch (Exception e) {
                LOG.error("Field:" + field.getName() + "\t|\t value:" + redisInfoMap.get(inputName), e);
            }
        }
    }
    return instance;
}

From source file:kina.utils.UtilMongoDB.java

/**
 * returns the id value annotated with @Field(fieldName = "_id")
 *
 * @param t   an instance of an object of type T to convert to BSONObject.
 * @param <T> the type of the object to convert.
 * @return the provided object converted to Object.
 * @throws IllegalAccessException//from  ww  w  .jav  a2  s. c om
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T extends KinaType> Object getId(T t)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Field[] fields = filterKinaFields(t.getClass());

    for (Field field : fields) {
        if (MONGO_DEFAULT_ID.equals(kinaFieldName(field))) {
            return Utils.findGetter(field.getName(), t.getClass()).invoke(t);
        }

    }

    return null;
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Inspects a {@link Model} class and returns all of the available and acceptable query parameter
 *   definitions, as a map of parameter names and {@link QueryParameterDescriptor} objects.
 * /*from w ww . ja  v  a  2 s .co  m*/
 * @param model
 * @return
 */
public static Map<String, QueryParameterDescriptor> getAvailableQueryParameters(Class<? extends Model<?>> model,
        boolean recursive) {
    Map<String, QueryParameterDescriptor> paramMap = new HashMap<>();
    for (Field field : model.getDeclaredFields()) {
        String fieldName = field.getName();
        Class<?> type = field.getType();
        if (Collection.class.isAssignableFrom(field.getType())) {
            ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            type = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        }
        if (field.isAnnotationPresent(Ignored.class)) {
            continue;
        } else {
            paramMap.put(fieldName,
                    new QueryParameterDescriptor(fieldName, fieldName, type, Evaluation.EQUALS));
        }
        if (field.isAnnotationPresent(ForeignKey.class)) {
            if (!recursive)
                continue;
            ForeignKey foreignKey = field.getAnnotation(ForeignKey.class);
            String relField = !"".equals(foreignKey.rel()) ? foreignKey.rel() : fieldName;
            Map<String, QueryParameterDescriptor> foreignModelMap = getAvailableQueryParameters(
                    foreignKey.model(), false);
            for (QueryParameterDescriptor descriptor : foreignModelMap.values()) {
                String newParamName = relField + "." + descriptor.getParamName();
                descriptor.setParamName(newParamName);
                paramMap.put(newParamName, descriptor);
            }
        }
        if (field.isAnnotationPresent(Aliases.class)) {
            Aliases aliases = field.getAnnotation(Aliases.class);
            for (Alias alias : aliases.value()) {
                paramMap.put(alias.value(),
                        new QueryParameterDescriptor(alias.value(),
                                alias.fieldName().equals("") ? fieldName : alias.fieldName(), type,
                                alias.evaluation()));
            }
        } else if (field.isAnnotationPresent(Alias.class)) {
            Alias alias = field.getAnnotation(Alias.class);
            paramMap.put(alias.value(), new QueryParameterDescriptor(alias.value(),
                    alias.fieldName().equals("") ? fieldName : alias.fieldName(), type, alias.evaluation()));
        }
    }
    return paramMap;
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parses object with follow rules:/*  ww w.jav a  2s.  c  o  m*/
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:gr.abiss.calipso.jpasearch.specifications.GenericSpecifications.java

public static Map<String, String[]> getSimpleSearchTerms(Class<?> clazz, String[] values) {
    Map<String, String[]> simpleSearchTerms = new HashMap<String, String[]>();
    Class<?> tmpClass = clazz;

    // try the cache first
    List<Field> simpleSearchFieldList = SIMPLE_SEARCH_FIELDs_CACHE.get(clazz);
    if (simpleSearchFieldList == null) {
        simpleSearchFieldList = new LinkedList<Field>();
        while (tmpClass != null) {
            for (Field tmpField : tmpClass.getDeclaredFields()) {
                String fieldName = tmpField.getName();
                // if string and not excluded
                if (isAcceptableSimpleSearchFieldClass(tmpField)
                        && !tmpField.isAnnotationPresent(Transient.class)
                        && !tmpField.isAnnotationPresent(JsonIgnore.class)) {

                    simpleSearchTerms.put(fieldName, values);
                    simpleSearchFieldList.add(tmpField);
                }//from ww  w.  j  av a 2s. co  m
            }
            tmpClass = tmpClass.getSuperclass();
        }
        // update the cache
        SIMPLE_SEARCH_FIELDs_CACHE.put(clazz, simpleSearchFieldList);
    } else {
        // use the caches field list
        for (Field tmpField : simpleSearchFieldList) {
            simpleSearchTerms.put(tmpField.getName(), values);
        }
    }
    return simpleSearchTerms;
}

From source file:net.minecraftforge.common.util.EnumHelper.java

private static void blankField(Class<?> enumClass, String fieldName) throws Exception {
    for (Field field : Class.class.getDeclaredFields()) {
        if (field.getName().contains(fieldName)) {
            field.setAccessible(true);/*from w  w w.  j  a v  a  2  s  . c  o m*/
            setFailsafeFieldValue(field, enumClass, null);
            break;
        }
    }
}

From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java

/**
 * Locates the resources in the configuration and distributed cache, etc., 
 * and sets them on the provided mapper instance.
 * /*from  ww w  .  j av  a 2  s .  com*/
 * @param bean            the object to inspect for resource annotations
 * @param config         the job configuration
 * @throws ToolException   if there are errors with reflection or the cache
 */
@SuppressWarnings("unchecked")
public static void initializeResources(Object bean, Configuration config) throws ToolException {
    try {
        List<Field> fields = MaraAnnotationUtil.INSTANCE.findAnnotatedFields(bean.getClass(), Resource.class);
        Path[] files = org.apache.hadoop.util.StringUtils
                .stringToPath(config.getStrings(MRJobConfig.CACHE_LOCALFILES));
        for (Field field : fields) {
            Resource resAnnotation = field.getAnnotation(Resource.class);
            String key = StringUtils.isEmpty(resAnnotation.name()) ? field.getName() : resAnnotation.name();
            String resourceId = config.get(CONFIGKEYBASE_RESOURCE + key);
            if (resourceId != null) {
                String[] parts = StringUtils.split(resourceId, VALUE_SEP);
                String className = parts[0];
                String valueString = parts[1];

                // Retrieve the value
                Object value = getResourceValue(field, valueString, className, files);

                setFieldValue(field, bean, value);
            }
        }
    } catch (IllegalArgumentException | IOException | ClassNotFoundException | IllegalAccessException e) {
        throw new ToolException(e);
    }
}

From source file:tv.arte.resteventapi.core.presentation.decoration.RestEventApiDecorationProvider.java

/**
 * Retrieve a decoration context related to a given bean
 * /*from  ww w. j  a va  2 s  .c o m*/
 * @param bean A given bean
 * @return A map with field names as keys and appropriate objects as values
 */
public static Map<String, ?> getBeanDecorationContext(final Object bean) {
    Map<String, Object> decorationContext = new LinkedHashMap<String, Object>();

    //Construct Hateoas self referencing link
    if (hrefedBeansControllerMethodMapping.containsKey(bean.getClass())) {
        Method method = hrefedBeansControllerMethodMapping.get(bean.getClass());
        final Map<String, Object> paramValue = new LinkedHashMap<String, Object>();

        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

                String hrefedValue = field.getAnnotation(HrefedParamField.class).value();

                if (StringUtils.isBlank(hrefedValue)) {
                    hrefedValue = field.getName();
                }

                Object fieldValue = null;
                try {
                    fieldValue = PropertyUtils.getProperty(bean, field.getName());
                } catch (Exception e) {
                    throw new RestEventApiRuntimeException("Unable to access the bean property value.");
                }
                if (fieldValue != null) {
                    paramValue.put(hrefedValue, fieldValue);
                }
            }
        }, new FieldFilter() {
            public boolean matches(Field field) {
                return field.isAnnotationPresent(HrefedParamField.class);
            }
        });

        decorationContext.put(HATEOAS_HREF_KEY, RestEventApiControllerLinkBuilder
                .linkTo(method.getDeclaringClass(), method, paramValue, conversionService));
    }

    return decorationContext;
}

From source file:com.all.shared.sync.SyncGenericConverter.java

public static <T> HashMap<String, Object> toMap(T clazz, SyncOperation op) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put(ENTITY, clazz.getClass().getSimpleName());
    for (Field field : clazz.getClass().getDeclaredFields()) {
        String name = field.getName();
        if (PropertyUtils.isReadable(clazz, name)) {
            try {
                Object attribute = PropertyUtils.getProperty(clazz, name);
                if (!field.isAnnotationPresent(Transient.class)) {
                    switch (op) {
                    case SAVE:
                        if (!(attribute instanceof Collection<?>)) {
                            map.put(name,
                                    attribute instanceof Date ? ((Date) attribute).getTime()
                                            : attribute instanceof SyncAble
                                                    ? ((SyncAble) attribute).getSyncAbleId()
                                                    : attribute);
                        }//from w  ww . j ava 2s .co m
                        break;
                    case UPDATE:
                        if (field.isAnnotationPresent(SyncUpdateAble.class)) {
                            map.put(name,
                                    attribute instanceof Date ? ((Date) attribute).getTime()
                                            : attribute instanceof SyncAble
                                                    ? ((SyncAble) attribute).getSyncAbleId()
                                                    : attribute);
                        }
                        break;
                    }
                    if (field.isAnnotationPresent(Id.class)) {
                        map.put(SYNC_HASHCODE, attribute);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("Could not execute method for attribute : " + name);
            }
        }
    }
    return map;
}

From source file:com.sunchenbin.store.feilong.core.lang.reflect.FieldUtil.java

/**
 * ?field?list./* w w w  .  j a v  a2 s .  c  om*/
 * 
 * <h3>??:</h3>
 * 
 * <blockquote>
 * <ol>
 * <li>{@code if isNullOrEmpty(fields)  return emptyList}</li>
 * <li>(?,) {@link #getAllFields(Object)}</li>
 * <li> <code>excludeFieldNames</code></li>
 * <li> {@link Modifier#isPrivate(int)} and {@link Modifier#isStatic(int)}</li>
 * </ol>
 * </blockquote>
 *
 * @param obj
 *            the obj
 * @param excludeFieldNames
 *            ?field names,?nullOrEmpty ?
 * @return the field value map
 * @see #getAllFields(Object)
 * @since 1.4.0
 */
public static List<Field> getAllFieldList(Object obj, String[] excludeFieldNames) {
    // (?,)
    Field[] fields = getAllFields(obj);

    if (Validator.isNullOrEmpty(fields)) {
        return Collections.emptyList();
    }

    List<Field> fieldList = new ArrayList<Field>();

    for (Field field : fields) {
        String fieldName = field.getName();

        if (Validator.isNotNullOrEmpty(excludeFieldNames)
                && ArrayUtils.contains(excludeFieldNames, fieldName)) {
            continue;
        }

        int modifiers = field.getModifiers();
        // ??? log
        boolean isPrivateAndStatic = Modifier.isPrivate(modifiers) && Modifier.isStatic(modifiers);
        LOGGER.debug("field name:[{}],modifiers:[{}],isPrivateAndStatic:[{}]", fieldName, modifiers,
                isPrivateAndStatic);

        if (!isPrivateAndStatic) {
            fieldList.add(field);
        }
    }
    return fieldList;
}