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:hu.javaforum.util.internal.ReflectionHelper.java

/**
 * Returns with the name of the field.//from www . j a  v  a2 s.c o  m
 * Returns:
 * - with annotated name, if the Field has XmlElement annotation
 * - otherwise with the name of the field
 *
 * @param field The Field instance
 * @return Field name as char array
 */
public static char[] getFieldName(final Field field) {
    if (field == null) {
        return new char[0];
    }

    if (XML_ELEMENT_LOADED) {
        final Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (XmlElement.class.equals(annotation.annotationType())) {
                if (!"##default".equals(((XmlElement) annotation).name())) {
                    return ((XmlElement) annotation).name().toCharArray();
                }
            }
        }
    }

    return field.getName().toCharArray();
}

From source file:kr.debop4j.core.tools.StringTool.java

/**
 * ??   ?, ? ? .  @param obj the obj/*w ww. j  a  va2  s.  co  m*/
 *
 * @param obj the obj
 * @return the string
 */
public static String objectToString(final Object obj) {
    if (obj == null)
        return NULL_STR;

    Objects.ToStringHelper helper = Objects.toStringHelper(obj);

    try {
        Class objClazz = obj.getClass();
        Field[] fields = objClazz.getFields();

        for (Field field : fields)
            helper.add(field.getName(), field.get(obj));

    } catch (IllegalAccessException ignored) {
        log.warn("  ? .", ignored);
    }
    return helper.toString();
}

From source file:com.sunchenbin.store.feilong.core.tools.jsonlib.JsonUtil.java

/**
 * ??filed ??./*from w w w.  j  a v a  2s .c  o m*/
 * 
 * <h3>??:</h3>
 * 
 * <blockquote>
 * <ol>
 * <li>field  {@link SensitiveWords}, {@link SensitiveWordsJsonValueProcessor}??</li>
 * </ol>
 * </blockquote>
 * 
 * @param obj
 *            the obj
 * @return the string
 * @see com.sunchenbin.store.feilong.core.lang.reflect.FieldUtil#getAllFieldNameAndValueMap(Object)
 * @see org.apache.commons.lang3.reflect.FieldUtils#getFieldsListWithAnnotation(Class, Class)
 * @since 1.4.0
 */
public static String formatObjectFiledsNameAndValueMap(Object obj) {
    Map<String, Object> map = FieldUtil.getAllFieldNameAndValueMap(obj);

    //*****************************************************************************
    List<Field> fieldsListWithAnnotation = FieldUtils.getFieldsListWithAnnotation(obj.getClass(),
            SensitiveWords.class);

    JsonFormatConfig jsonFormatConfig = null;
    if (Validator.isNotNullOrEmpty(fieldsListWithAnnotation)) {
        SensitiveWordsJsonValueProcessor sensitiveWordsJsonValueProcessor = new SensitiveWordsJsonValueProcessor();

        Map<String, JsonValueProcessor> propertyNameAndJsonValueProcessorMap = new HashMap<String, JsonValueProcessor>();
        for (Field field : fieldsListWithAnnotation) {
            propertyNameAndJsonValueProcessorMap.put(field.getName(), sensitiveWordsJsonValueProcessor);
        }

        jsonFormatConfig = new JsonFormatConfig();
        jsonFormatConfig.setPropertyNameAndJsonValueProcessorMap(propertyNameAndJsonValueProcessorMap);
    }

    return format(map, jsonFormatConfig);
}

From source file:bdi4jade.util.ReflectionUtils.java

/**
 * Sets plan body fields annotated with {@link bdi4jade.annotation.Belief}.
 * /*from   ww  w  . ja  v  a  2 s .c  o  m*/
 * @param planBody
 *            the plan body to be setup with beliefs.
 */
public static void setupBeliefs(PlanBody planBody) {
    Capability capability = planBody.getPlan().getPlanLibrary().getCapability();
    Class<?> currentClass = planBody.getClass();
    while (PlanBody.class.isAssignableFrom(currentClass)) {
        for (Field field : currentClass.getDeclaredFields()) {
            boolean b = field.isAccessible();
            field.setAccessible(true);
            try {
                if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                    if (Belief.class.isAssignableFrom(field.getType())) {
                        bdi4jade.annotation.Belief beliefAnnotation = field
                                .getAnnotation(bdi4jade.annotation.Belief.class);
                        String beliefName = beliefAnnotation.name();
                        if (beliefName == null || "".equals(beliefName)) {
                            beliefName = field.getName();
                        }
                        Belief<?, ?> belief = capability.getBeliefBase().getBelief(beliefName);
                        field.set(planBody, belief);
                    } else {
                        throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                    }
                }
            } catch (Exception exc) {
                log.warn(exc);
            }
            field.setAccessible(b);
        }
        currentClass = currentClass.getSuperclass();
    }
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Retrieve all fields deemed as Exposed, i.e. they are public or have a public accessor method or are marked by an
 * annotation to be exposed.//from w ww . j  a  v  a  2 s.  co  m
 *
 * @param clazz cannot be <code>null</code>.
 * @return
 */
public static List<ReflectedInfo> getExposedFieldInfo(final Class<?> clazz) {
    List<ReflectedInfo> results = null;
    try {
        results = fieldInfoCache.get(clazz, new Callable<List<ReflectedInfo>>() {
            /**
             * This method is called if the value is not found in the cache. This
             * is where the real reflection work is done.
             */
            public List<ReflectedInfo> call() throws Exception {
                List<ReflectedInfo> exposed = new ArrayList<ReflectedInfo>();
                for (Method m : clazz.getMethods()) {
                    if (ReflectionUtils.isGetter(m) && !isIgnored(m)) {
                        Field f = getGetterField(m);
                        if (f != null && !isIgnored(f)) {
                            f.setAccessible(true);
                            Siren4JProperty propAnno = f.getAnnotation(Siren4JProperty.class);
                            String effectiveName = propAnno != null
                                    ? StringUtils.defaultIfEmpty(propAnno.name(), f.getName())
                                    : f.getName();
                            Siren4JSubEntity subAnno = f.getAnnotation(Siren4JSubEntity.class);
                            if (subAnno != null && !ArrayUtils.isEmpty(subAnno.rel())) {
                                effectiveName = subAnno.rel().length == 1 ? subAnno.rel()[0]
                                        : ArrayUtils.toString(subAnno.rel());
                            }
                            exposed.add(new ReflectedInfo(f, m, ReflectionUtils.getSetter(clazz, f),
                                    effectiveName));
                        }
                    }
                }
                return exposed;
            }

        });
    } catch (ExecutionException e) {
        throw new Siren4JRuntimeException(e);
    }
    return results;

}

From source file:com.phoenixnap.oss.ramlapisync.naming.SchemaHelper.java

/**
 * Breaks down a class into component fields which are mapped as Query Parameters. If Javadoc is supplied, this will
 * be injected as comments// www .j a  v a2 s .co  m
 * 
 * @param param The Parameter representing the class to be converted into query parameters
 * @param javaDocStore The associated JavaDoc (if any)
 * @return a Map of Parameter RAML models keyed by parameter name
 */
public static Map<String, QueryParameter> convertClassToQueryParameters(final Parameter param,
        final JavaDocStore javaDocStore) {
    final Map<String, QueryParameter> outParams = new TreeMap<>();

    if (param == null || param.equals(Void.class)) {
        return outParams;
    }
    final ApiParameterMetadata parameterMetadata = new ApiParameterMetadata(param);

    if (mapSimpleType(param.getType()) != null) {
        throw new IllegalArgumentException(
                "This method should only be called on non primitive classes which will be broken down into query parameters");
    }

    try {
        for (Field field : param.getType().getDeclaredFields()) {
            if (!java.lang.reflect.Modifier.isStatic(field.getModifiers())
                    && !java.lang.reflect.Modifier.isTransient(field.getModifiers())
                    && !java.lang.reflect.Modifier.isVolatile(field.getModifiers())) {
                QueryParameter queryParam = new QueryParameter();

                // Check if we have comments
                JavaDocEntry paramComment = javaDocStore == null ? null
                        : javaDocStore.getJavaDoc(field.getName());
                if (paramComment != null && StringUtils.hasText(paramComment.getComment())) {
                    queryParam.setDescription(paramComment.getComment());
                }

                // Populate parameter model with data such as name, type and
                // required/not
                queryParam.setDisplayName(field.getName());
                ParamType simpleType = mapSimpleType(field.getType());
                queryParam.setType(simpleType == null ? ParamType.STRING : simpleType);
                queryParam.setRequired(parameterMetadata.isNullable());
                queryParam.setRepeat(false); // TODO we could add validation
                // info
                // here - maybe hook into
                // JSR303
                // annotations
                outParams.put(field.getName(), queryParam);
            }
        }
        return outParams;

    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Convert ISO attr parts into attribute names
 *
 * Expected formats: List< Map< String, List< Map< String, List<?> > > > > ?
 * can be String or a Map<String, String>
 * [{item<gov.nih.nci.iso21090.Ad>=[{part_0=[value, code, codeSystem,
 * {type=[AL]}]}, {part_1=[value, code, codeSystem, {type=[AL]}]}]}]
 * resulting: item.part_0.value, item.part_0.code, item.part_0.codeSystem,
 * item.part_0.type, item.part_1.value, item.part_1.code,
 * item.part_1.codeSystem, item.part_1.type
 *
 * @param attrs//  w  w  w.  ja va2s .  c  om
 * @return
 */
public static List<String> getSearchableIsoDataTypeFieldsForDsetAd(Field field, List attrs) {

    String fieldName = field.getName();
    List<String> fnAttrs = new ArrayList();
    // List of ISO fields
    Iterator iter = attrs.iterator();
    while (iter.hasNext()) {
        Object obj = iter.next();
        if (obj instanceof java.lang.String) {
            // log.debug("instanceof java.lang.String*******" +
            // obj);
            fnAttrs.add((String) obj);
        } else if (obj instanceof java.util.Map) {
            // log.debug("instanceof java.util.Map*******" +
            // obj);
            Map attrMap = (Map) obj;
            Iterator mapIter = attrMap.keySet().iterator();
            while (mapIter.hasNext()) {
                // item<gov.nih.nci.iso21090.Ad>
                String keyName = (String) mapIter.next();
                String subAttrName = keyName;
                if (keyName.indexOf("<") > 0) {
                    subAttrName = keyName.substring(0, keyName.indexOf("<"));
                }

                // [{part_0=[value, code, codeSystem, {type=[AL]}]},
                // {part_1=[value, code, codeSystem, {type=[AL]}]}]
                Object mapKeyObj = attrMap.get(keyName);
                if (mapKeyObj instanceof java.util.List) {
                    // log.debug("instanceof java.util.List*******"
                    // + mapKeyObj);
                    List mapKeyObjValue = (List) attrMap.get(keyName);
                    Iterator mapKeyObjValueIter = mapKeyObjValue.iterator();

                    while (mapKeyObjValueIter.hasNext()) {
                        List<String> subAttrNames = new ArrayList();
                        Object mapKeyObjValueObj = mapKeyObjValueIter.next();
                        if (mapKeyObjValueObj instanceof String) {
                            fnAttrs.add(fieldName + "." + subAttrName + "." + mapKeyObjValueObj);
                        } else {
                            // System.out
                            // .println("instanceof not String *******"
                            // + mapKeyObj);
                            convertISOPart(subAttrName, (java.util.Map) mapKeyObjValueObj, subAttrNames);
                            for (String partAttrName : subAttrNames) {

                                String newPartName = partAttrName;
                                log.debug("newPartName: " + newPartName);
                                if (newPartName.indexOf("part_") != -1) {
                                    newPartName = "part" + partAttrName.substring(
                                            partAttrName.indexOf("part_") + 5, partAttrName.length());
                                    log.debug("newPartName: " + newPartName);
                                }

                                fnAttrs.add(fieldName + "." + subAttrName + "." + newPartName);
                            }
                        }
                    }

                } else if (mapKeyObj instanceof java.util.Map) {
                    // log.debug("instanceof java.util.Map ----- "
                    // + mapKeyObj);
                    convertISOPart(subAttrName, (java.util.Map) mapKeyObj, fnAttrs);
                } else {
                    // log.debug("instanceof I do not know ----- "
                    // + mapKeyObj);
                }

            }
        }
    }
    // log.debug("returning DsetAd fnAttrs: " + fnAttrs);
    /*
     * List returnList = new ArrayList(); for(String attName : fnAttrs) {
     * returnList.add(fieldName+"."+attName); }
     */
    return fnAttrs;
}

From source file:com.helpinput.core.Utils.java

public static void object2Buffer(Object o, Class<?> targetClass, StringBuffer sb) {
    Field[] fields = targetClass.getDeclaredFields();
    for (Field field : fields) {
        Object value = getFieldValue(o, field);
        if (value != null) {
            String fieldName = field.getName();
            if (!fieldName.equals("descriptors")) {
                sb.append(field.getName() + "=" + value);
                sb.append(" , ");
                sb.append(" \n");
            }//w ww . j  a va2 s.c  o  m
        }
    }

    Class<?> supClass = targetClass.getSuperclass();
    if (supClass != null)
        object2Buffer(o, supClass, sb);
}

From source file:adalid.core.XS1.java

private static Field getField(String name, Class<?> type, Class<?> top) {
    if (StringUtils.isNotBlank(name)) {
        if (top.isAssignableFrom(type)) {
            for (Field field : getFields(type, top)) {
                field.setAccessible(true);
                if (name.equals(field.getName())) {
                    return field;
                }/*from w  ww  .j a  va 2  s .c  o m*/
            }
        }
    }
    return null;
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

private static <T> void parent(Class<T> parentClass, Set<String> set, List<String> result) {
    Field[] fs = parentClass.getDeclaredFields();

    for (Field f : fs) {

        WebParam itemField = f.getAnnotation(WebParam.class);
        if (itemField == null) {
            continue;
        }//  w w  w  .  j  av a 2 s .c  o  m
        if ("".equals(itemField.value())) {
            String fname = f.getName();
            if (!set.contains(fname)) {
                set.add(fname);
                result.add(fname);
            }
        } else {
            String fname = itemField.value();
            if (!set.contains(fname)) {
                set.add(fname);
                result.add(fname);
            }
        }

    }
}