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:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Convert ISO attr parts into attribute names Expected formats: List< Map<
 * String, List<?> > > ? can be String or a Map<String, String>
 * [{part_0=[value, code, codeSystem, {type=[AL]}]}, {part_1=[value, code,
 * codeSystem, {type=[AL]}]}] resulting: part_0.value, part_0.code,
 * part_0.codeSystem, part_0.type, part_1.value, part_1.code,
 * part_1.codeSystem, part_1.type/*from   www .j  a  v  a  2 s.  c  o  m*/
 *
 * @param field
 * @param attrs
 * @return
 */
public static List<String> getSearchableIsoDataTypeFieldsForSc(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 String) {
            fnAttrs.add(fieldName + "." + obj);
        } else {
            Map attrMap = (Map) obj;
            Iterator mapIter = attrMap.keySet().iterator();
            while (mapIter.hasNext()) {
                // part_0
                String keyName = (String) mapIter.next();

                // value, code, codeSystem, {type=[AL]}
                Object mapKeyObj = attrMap.get(keyName);
                // 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 + "." + keyName + "." + mapKeyObjValueObj);
                    } else {
                        // log.debug("instanceof not String *******"
                        // + mapKeyObj);
                        java.util.Map mapKeyObjValueMap = (java.util.Map) mapKeyObjValueObj;
                        String key = (String) mapKeyObjValueMap.keySet().iterator().next();
                        fnAttrs.add(fieldName + "." + keyName + "." + key);
                    }
                }

            }
        }
    }
    // log.debug("returning Ad fnAttrs: " + fnAttrs);
    return fnAttrs;
}

From source file:ca.uhn.fhir.context.ModelScanner.java

static Class<?> determineElementType(Field next) {
    Class<?> nextElementType = next.getType();
    if (List.class.equals(nextElementType)) {
        nextElementType = ReflectionUtil.getGenericCollectionTypeOfField(next);
    } else if (Collection.class.isAssignableFrom(nextElementType)) {
        throw new ConfigurationException(
                "Field '" + next.getName() + "' in type '" + next.getClass().getCanonicalName()
                        + "' is a Collection - Only java.util.List curently supported");
    }//from   w w  w. j  ava  2s. c  o m
    return nextElementType;
}

From source file:de.micromata.genome.tpsb.CommonTestBuilder.java

private static void populate(Object bean, Map<String, Object> properties) {
    for (Map.Entry<String, Object> me : properties.entrySet()) {
        Field f = PrivateBeanUtils.findField(bean, me.getKey());
        if (f == null) {
            continue;
        }//from  w  w w.j a v  a2s . c o  m
        try {
            PrivateBeanUtils.writeField(bean, f, me.getValue());
        } catch (Exception ex) {
            LOG.warn("Cannot copy var: " + f.getName() + " to " + bean.getClass().getName() + ": "
                    + ex.getMessage(), ex);
        }
    }
}

From source file:adalid.core.XS1.java

static void logDuplicateAnnotation(Field field, Class<? extends Annotation> annotation, Field previous) {
    String name = field.getName();
    Class<?> type = field.getDeclaringClass();
    String string = previous + " has the same annotation";
    logFieldAnnotationErrorMessage(name, type, annotation, string);
}

From source file:com.datatorrent.lib.util.PojoUtils.java

/**
 * Return the getter expression for the given field.
 * <p>/*from ww w .  jav  a  2 s. c  o  m*/
 * If the field is a public member, the field name is used else the getter function. If no matching field or getter
 * method is found, the expression is returned unmodified.
 *
 * @param pojoClass class to check for the field
 * @param fieldExpression field name expression
 * @param exprClass expected field type
 * @return java code fragment
 */
private static String getSingleFieldGetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaReturnStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32,
            exprClass);
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(field.getType(), exprClass)) {
            return code.append(field.getName()).getStatement();
        }
        logger.debug("Field {} can not be assigned to {}. Proceeding to locate a getter method.", field,
                exprClass);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass,
                fieldExpression);
    }

    String methodName = GET + upperCaseWord(fieldExpression);
    try {
        Method method = pojoClass.getMethod(methodName);
        if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) {
            return code.append(methodName).append("()").getStatement();
        }
        logger.debug(
                "method {} of the {} returns {} that can not be assigned to {}. Proceeding to locate another getter method.",
                pojoClass, methodName, method.getReturnType(), exprClass);
    } catch (NoSuchMethodException | SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass,
                methodName);
    }

    methodName = IS + upperCaseWord(fieldExpression);
    try {
        Method method = pojoClass.getMethod(methodName);
        if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) {
            return code.append(methodName).append("()").getStatement();
        }
        logger.debug(
                "method {} of the {} returns {} that can not be assigned to {}. Proceeding with the original expression {}.",
                pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression);
    } catch (NoSuchMethodException | SecurityException ex) {
        logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass,
                methodName, fieldExpression);
    }

    return code.append(fieldExpression).getStatement();
}

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

/**
 * Convert ISO attr parts into attribute names Expected formats: List< Map<
 * String, List<?> > > ? can be String or a Map<String, String>
 * [{part_0=[value, code, codeSystem, {type=[AL]}]}, {part_1=[value, code,
 * codeSystem, {type=[AL]}]}] resulting: part_0.value, part_0.code,
 * part_0.codeSystem, part_0.type, part_1.value, part_1.code,
 * part_1.codeSystem, part_1.type//from   w  w w  .  j av a  2 s  .  c  o m
 *
 * @param field
 * @param attrs
 * @return
 */
public static List<String> getSearchableIsoDataTypeFieldsForAd(Field field, List attrs) {
    String fieldName = field.getName();
    log.debug("fieldName: " + fieldName);
    String fieldNameWithoutU = fieldName;
    if (fieldName.indexOf("_") > 0)
        fieldNameWithoutU = fieldName.substring(0, fieldName.indexOf("_"))
                + fieldName.substring(fieldName.indexOf("_") + 1, fieldName.length());
    log.debug("fieldNameWithoutU: " + fieldNameWithoutU);

    List<String> fnAttrs = new ArrayList();
    // List of ISO fields
    Iterator iter = attrs.iterator();
    while (iter.hasNext()) {
        Object obj = iter.next();
        Map attrMap = (Map) obj;
        Iterator mapIter = attrMap.keySet().iterator();
        while (mapIter.hasNext()) {
            // part_0
            String keyName = (String) mapIter.next();
            log.debug("keyName: " + keyName);
            String keyNameWithoutU = keyName;
            if (keyName.indexOf("_") > 0)
                keyNameWithoutU = keyName.substring(0, keyName.indexOf("_"))
                        + keyName.substring(keyName.indexOf("_") + 1, keyName.length());
            log.debug("keyNameWithoutU: " + keyNameWithoutU);
            // value, code, codeSystem, {type=[AL]}
            Object mapKeyObj = attrMap.get(keyName);
            // 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 + "." + keyNameWithoutU + "." + mapKeyObjValueObj);
                } else {
                    // log.debug("instanceof not String *******"
                    // + mapKeyObj);
                    java.util.Map mapKeyObjValueMap = (java.util.Map) mapKeyObjValueObj;
                    String key = (String) mapKeyObjValueMap.keySet().iterator().next();
                    fnAttrs.add(fieldName + "." + keyNameWithoutU + "." + key);
                }
            }

        }
    }
    log.debug("returning Ad fnAttrs: " + fnAttrs);
    return fnAttrs;
}

From source file:eu.crisis_economics.abm.model.ModelUtils.java

/**
  * A depth-first recursive parameter search tool. This function accepts an object
  * ({@code X}) and a {@link String} ID ({@code P}) of a parameter to search for.<br><br>
  * /*from  w w w .j a  va 2 s .  co m*/
  * Any object {@code O} in the configuration hierarchy of {@code X} which possesses a field with
  * a) the appropriate annotation and b) parameter ID is identified and returned.
  * This method will search for member fields {@code F} (with any modifer) which satisfy:
  * 
  * <ul>
  *   <li> {@code F} carries a {@link Parameter} {@link Annotation}.
  *   <li> The {@code ID} of this {@link Parameter} is equal to {@code P}.
  *   <li> {@code F} does not itself belongs to a {@link Submodel} field that satisfies the
  *        above two conditions.
  * </ul>
  * 
  * This search operates as follows:<br><br>
  * 
  * <ul>
  *   <li> If {@code X} contains a member field {@code F} satisfying the above conditions, 
  *        {@code F} is accepted and returned.
  *   <li> Otherwise, each supertype in the inheritance hierarchy of {@code X} is searched.
  *   <li> Apply the above steps recursively (depth-first) to every field {@code F}
  *        in {@code X} annotated with {@link Submodel}, unless {@code F} itself
  *        satisfies the above conditions, in which case {@code F} is accepted and returned.
  * </ul>
  * 
  * This method returns a {@link List} of {@link ConfigurationModifier} objects. Each element
  * in this list corresponds to a field {@code F} somewhere in the inheritance hierarchy of
  * {@code X} which satisfied the above search conditions. {@link ConfigurationModifier}
  * objects facilitate direct changes to the value of each such {@code F}.<br><br>
  * 
  * @param on (<code>X</code>) <br>
  *        The object to search.
  * @param parameterIdToFind on (<code>P</code>) <br>
  *        The ID of the {@link Parameter} to search for.
  */
public static List<ConfigurationModifier> search(final Object on, final String parameterIdToFind) {
    if (on == null)
        throw new IllegalArgumentException("search: object to search is null.");
    if (parameterIdToFind == null || parameterIdToFind.isEmpty())
        throw new IllegalArgumentException("search: parameter name is empty or null.");
    if (VERBOSE_MODE)
        System.out.println("search: searching object " + on.getClass().getSimpleName() + on.hashCode()
                + " for parameters of type " + parameterIdToFind + ".");
    final Class<?> objClass = on.getClass();
    final List<ConfigurationModifier> methodsIdentified = new ArrayList<ConfigurationModifier>();
    for (Class<?> typeToSearch = objClass; typeToSearch != null; typeToSearch = typeToSearch.getSuperclass()) {
        for (final Field field : typeToSearch.getDeclaredFields()) {
            field.setAccessible(true);
            if (VERBOSE_MODE)
                System.out.println("inspecting field with name: " + field.getName() + ".");
            try {
                Annotation drilldownAnnotation = null, modelParameterAnnotation = null;
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() == Submodel.class.getName()) { // Proxies
                        drilldownAnnotation = element;
                        if (VERBOSE_MODE)
                            System.out.println("field " + field.getName() + " is a subconfiguration.");
                        continue;
                    } else if (element.annotationType().getName() == Parameter.class.getName()) { // Proxies
                        final Class<? extends Annotation> type = element.annotationType();
                        final String id = (String) type.getMethod("ID").invoke(element);
                        if (parameterIdToFind.equals(id)) {
                            modelParameterAnnotation = element;
                            if (VERBOSE_MODE)
                                System.out.println("* field is valid.");
                            continue;
                        } else if (VERBOSE_MODE)
                            System.out.println("field ID [" + id + "] does not match the required ID: "
                                    + parameterIdToFind + ".");
                        continue;
                    } else
                        continue;
                }
                if (modelParameterAnnotation != null) {
                    final ConfigurationModifier fieldWithMutators = findGetterSetterMethods(field, on,
                            parameterIdToFind);
                    methodsIdentified.add(fieldWithMutators);
                    continue;
                } else if (drilldownAnnotation != null) {
                    if (VERBOSE_MODE)
                        System.out.println("descending into subconfiguration: " + field.getName());
                    final Object fieldValue = field.get(on);
                    methodsIdentified.addAll(search(fieldValue, parameterIdToFind));
                    continue;
                }
                if (VERBOSE_MODE)
                    System.out.println("rejecting parameter: " + field.getName());
            } catch (final SecurityException e) {
                throw new IllegalStateException(
                        "search: a security exception was raised when testing a field with name "
                                + field.getName() + " for model parameter annotations. Details follow: "
                                + e.getMessage() + ".");
            } catch (final IllegalArgumentException e) {
                throw new IllegalStateException(
                        "search: an illegal argument exception was raised when testing a field with name "
                                + field.getName() + " for model parameter annotations. Details follow: "
                                + e.getMessage() + ".");
            } catch (final IllegalAccessException e) {
                throw new IllegalStateException(
                        "search: a security exception was raised when testing a field with name "
                                + field.getName() + " for model parameter annotations. Details follow: "
                                + e.getMessage() + ".");
            } catch (final InvocationTargetException e) {
                throw new IllegalStateException(
                        "search: an invokation target exception was raised when testing a field with" + " name "
                                + field.getName() + " for model parameter annotations. Details follow: "
                                + e.getMessage() + ".");
            } catch (final NoSuchMethodException e) {
                throw new IllegalStateException(
                        "search: a missing-method exception was raised when testing a field with name "
                                + field.getName() + " for model parameter annotations. Details follow: "
                                + e.getMessage() + ".");
            }
        }
    }
    if (VERBOSE_MODE)
        System.out.println("searched: " + on.getClass().getSimpleName() + on.hashCode()
                + " for parameters of type " + parameterIdToFind + ".");
    return methodsIdentified;
}

From source file:org.uimafit.factory.ConfigurationParameterFactory.java

/**
 * This method generates the default name of a configuration parameter that is defined by an
 * {@link org.uimafit.descriptor.ConfigurationParameter} annotation when no name is given
 *//*from w  w w  .java2s  .  c om*/
public static String getConfigurationParameterName(Field field) {
    if (isConfigurationParameterField(field)) {
        org.uimafit.descriptor.ConfigurationParameter annotation = field
                .getAnnotation(org.uimafit.descriptor.ConfigurationParameter.class);
        String name = annotation.name();
        if (name.equals(org.uimafit.descriptor.ConfigurationParameter.USE_FIELD_NAME)) {
            name = field.getDeclaringClass().getName() + "." + field.getName();
        }
        return name;
    }
    return null;
}

From source file:eagle.log.entity.meta.EntityDefinitionManager.java

@SuppressWarnings("unchecked")
public static EntityDefinition createEntityDefinition(Class<? extends TaggedLogAPIEntity> cls) {

    final EntityDefinition ed = new EntityDefinition();

    ed.setEntityClass(cls);//from  ww w .  j a va 2s  .c o m
    // parse cls' annotations
    Table table = cls.getAnnotation(Table.class);
    if (table == null || table.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty table name annotated with @Table");
    }
    String tableName = table.value();
    if (EagleConfigFactory.load().isTableNamePrefixedWithEnvironment()) {
        tableName = EagleConfigFactory.load().getEnv() + "_" + tableName;
    }
    ed.setTable(tableName);

    ColumnFamily family = cls.getAnnotation(ColumnFamily.class);
    if (family == null || family.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty column family name annotated with @ColumnFamily");
    }
    ed.setColumnFamily(family.value());

    Prefix prefix = cls.getAnnotation(Prefix.class);
    if (prefix == null || prefix.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty prefix name annotated with @Prefix");
    }
    ed.setPrefix(prefix.value());

    TimeSeries ts = cls.getAnnotation(TimeSeries.class);
    if (ts == null) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty timeseries name annotated with @TimeSeries");
    }
    ed.setTimeSeries(ts.value());

    Service service = cls.getAnnotation(Service.class);
    if (service == null || service.value().isEmpty()) {
        ed.setService(cls.getSimpleName());
    } else {
        ed.setService(service.value());
    }

    Metric m = cls.getAnnotation(Metric.class);
    Map<String, Class<?>> dynamicFieldTypes = new HashMap<String, Class<?>>();
    if (m != null) {
        // metric has to be timeseries
        if (!ts.value()) {
            throw new IllegalArgumentException("Metric entity must be time series as well");
        }
        MetricDefinition md = new MetricDefinition();
        md.setInterval(m.interval());
        ed.setMetricDefinition(md);
    }

    java.lang.reflect.Field[] fields = cls.getDeclaredFields();
    for (java.lang.reflect.Field f : fields) {
        Column column = f.getAnnotation(Column.class);
        if (column == null || column.value().isEmpty()) {
            continue;
        }
        Class<?> fldCls = f.getType();
        // intrusive check field type for metric entity
        checkFieldTypeForMetric(ed.getMetricDefinition(), f.getName(), fldCls, dynamicFieldTypes);
        Qualifier q = new Qualifier();
        q.setDisplayName(f.getName());
        q.setQualifierName(column.value());
        EntitySerDeser<?> serDeser = _serDeserMap.get(fldCls);
        if (serDeser == null) {
            throw new IllegalArgumentException(fldCls.getName() + " in field " + f.getName() + " of entity "
                    + cls.getSimpleName() + " has no serializer associated ");
        } else {
            q.setSerDeser((EntitySerDeser<Object>) serDeser);
        }
        ed.getQualifierNameMap().put(q.getQualifierName(), q);
        ed.getDisplayNameMap().put(q.getDisplayName(), q);
        // TODO: should refine rules, consider fields like "hCol", getter method should be gethCol() according to org.apache.commons.beanutils.PropertyUtils
        final String propertyName = f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
        String getterName = "get" + propertyName;
        try {
            Method method = cls.getMethod(getterName);
            ed.getQualifierGetterMap().put(f.getName(), method);
        } catch (Exception e) {
            // Check if the type is boolean
            getterName = "is" + propertyName;
            try {
                Method method = cls.getMethod(getterName);
                ed.getQualifierGetterMap().put(f.getName(), method);
            } catch (Exception e1) {
                throw new IllegalArgumentException(
                        "Field " + f.getName() + " hasn't defined valid getter method: " + getterName, e);
            }
        }
        if (LOG.isDebugEnabled())
            LOG.debug("Field registered " + q);
    }

    // TODO: Lazy create because not used at all
    // dynamically create bean class
    if (ed.getMetricDefinition() != null) {
        Class<?> metricCls = createDynamicClassForMetric(cls.getName() + "_SingleTimestamp", dynamicFieldTypes);
        ed.getMetricDefinition().setSingleTimestampEntityClass(metricCls);
    }

    final Partition partition = cls.getAnnotation(Partition.class);
    if (partition != null) {
        final String[] partitions = partition.value();
        ed.setPartitions(partitions);
        // Check if partition fields are all tag fields. Partition field can't be column field, must be tag field.
        for (String part : partitions) {
            if (!ed.isTag(part)) {
                throw new IllegalArgumentException("Partition field can't be column field, must be tag field. "
                        + "Partition name: " + part);
            }
        }
    }

    final Indexes indexes = cls.getAnnotation(Indexes.class);
    if (indexes != null) {
        final Index[] inds = indexes.value();
        final IndexDefinition[] indexDefinitions = new IndexDefinition[inds.length];
        for (int i = 0; i < inds.length; ++i) {
            final Index ind = inds[i];
            indexDefinitions[i] = new IndexDefinition(ed, ind);
        }
        ed.setIndexes(indexDefinitions);
    }

    final ServicePath path = cls.getAnnotation(ServicePath.class);
    if (path != null) {
        if (path.path() != null && (!path.path().isEmpty())) {
            ed.setServiceCreationPath(path.path());
        }
    }

    return ed;
}

From source file:com.github.jinahya.sql.database.metadata.bind.MetadataContext.java

private static String suppression(final Class<?> beanClass, final Field beanField) {

    return decapitalize(beanClass.getSimpleName()) + "/" + beanField.getName();
}