Example usage for java.lang.reflect Field getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * Tests whether the given field of input has this annotation.
 * //from  w w  w.  j a  va2  s  . c om
 * @param input
 *          the input
 * @param fieldName
 *          the field name
 * @param annotationClass
 *          the annotation class
 * @return true, if successful
 */
public static boolean hasAnnotation(final Object input, final String fieldName,
        final Class<? extends Annotation> annotationClass) {
    final Field declaredField = getField(input, fieldName);
    if (declaredField == null) {
        return false;
    }
    return declaredField.getAnnotation(annotationClass) != null;
}

From source file:eu.udig.omsbox.utils.OmsBoxUtils.java

private static void collectParameters(StringBuilder sbTmp, Collection<Access> accessList) throws Exception {
    for (Access access : accessList) {
        Field field = access.getField();
        String fieldName = field.getName();
        Description descriptionAnnot = field.getAnnotation(Description.class);

        if (fieldName.equals("pm")) {
            // ignore progress monitor
            continue;
        }//from  w ww.j  ava  2  s.  c om
        String fieldDescription = " - ";
        if (descriptionAnnot != null) {
            fieldDescription = AnnotationUtilities.getLocalizedDescription(descriptionAnnot);
            if (fieldDescription == null) {
                fieldDescription = " - ";
            }

            Unit unitAnn = field.getAnnotation(Unit.class);
            if (unitAnn != null) {
                fieldDescription = fieldDescription + " [" + unitAnn.value() + "]";
            }
        }

        sbTmp.append("<tr>").append(NEWLINE);
        sbTmp.append("<td width=\"40%\"> <b>").append(fieldName).append("</b> </td><td width=\"60%\"> ");
        sbTmp.append(fieldDescription).append(" </td>").append(NEWLINE);
        sbTmp.append("</tr>").append(NEWLINE);
    }
}

From source file:com.taobao.android.builder.tools.guide.AtlasConfigHelper.java

private static void readConfig(Object object, String prefix, List<AtlasConfigField> configFieldList,
        int groupOrder, String variantName) throws IllegalAccessException {

    if (null == object) {
        return;//ww  w .j ava  2 s. co m
    }

    for (Field field : getAllFields(object.getClass())) {

        field.setAccessible(true);

        Config config = field.getAnnotation(Config.class);
        if (null != config) {
            AtlasConfigField configField = new AtlasConfigField();
            configField.name = prefix + "." + field.getName();
            configField.order = config.order();
            configField.desc = config.message();
            Object obj = field.get(object);
            configField.value = (null == obj ? null : String.valueOf(obj));
            configField.groupOrder = groupOrder;
            configField.variantName = variantName;
            configField.type = field.getType().getSimpleName();
            configField.advanced = config.advance();
            configField.group = config.group();
            configFieldList.add(configField);
            continue;
        }

        ConfigGroup configGroup = field.getAnnotation(ConfigGroup.class);
        if (null != configGroup) {

            Object nestedValue = field.get(object);

            if (nestedValue instanceof NamedDomainObjectContainer) {

                readConfig(((NamedDomainObjectContainer) nestedValue).maybeCreate("debug"),
                        prefix + "." + field.getName() + ".debug", configFieldList, configGroup.order(),
                        "debug");
                readConfig(((NamedDomainObjectContainer) nestedValue).maybeCreate("release"),
                        prefix + "." + field.getName() + ".release", configFieldList, configGroup.order(),
                        "release");
            } else {

                readConfig(nestedValue, prefix + "." + field.getName(), configFieldList, configGroup.order(),
                        "");
            }
        }
    }
}

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

/**
 * Checks a request parameter name against all possible {@link Model} attributes, converting it to
 *   the appropriate repository field name for querying and sorting.
 *
 * @param param//from ww  w.j  a v  a2  s.c  o m
 * @return
 */
public static String remapParameterName(String param, Class<? extends Model<?>> model) {
    logger.debug(String.format("Attempting to remap query string parameter: %s", param));
    for (Field field : model.getDeclaredFields()) {
        String fieldName = field.getName();
        if (field.isAnnotationPresent(Aliases.class)) {
            Aliases aliases = field.getAnnotation(Aliases.class);
            for (Alias alias : aliases.value()) {
                if (alias.value().equals(param))
                    return fieldName;
            }
        } else if (field.isAnnotationPresent(Alias.class)) {
            Alias alias = field.getAnnotation(Alias.class);
            if (alias.value().equals(param))
                return fieldName;
        }
    }
    logger.debug(String.format("Parameter remapped to: %s", param));
    return param;
}

From source file:cn.afterturn.easypoi.util.PoiPublicUtil.java

/**
 * ???excel?/*from  w  w  w.  j  av  a  2s.  c  o m*/
 *
 * @param exclusionsList
 * @param field
 * @param targetId
 * @return
 */
public static boolean isNotUserExcelUserThis(List<String> exclusionsList, Field field, String targetId) {
    boolean boo = true;
    if (field.getAnnotation(ExcelIgnore.class) != null) {
        boo = true;
    } else if (boo && field.getAnnotation(ExcelCollection.class) != null
            && isUseInThis(field.getAnnotation(ExcelCollection.class).name(), targetId)
            && (exclusionsList == null
                    || !exclusionsList.contains(field.getAnnotation(ExcelCollection.class).name()))) {
        boo = false;
    } else if (boo && field.getAnnotation(Excel.class) != null
            && isUseInThis(field.getAnnotation(Excel.class).name(), targetId)
            && (exclusionsList == null || !exclusionsList.contains(field.getAnnotation(Excel.class).name()))) {
        boo = false;
    } else if (boo && field.getAnnotation(ExcelEntity.class) != null
            && isUseInThis(field.getAnnotation(ExcelEntity.class).name(), targetId) && (exclusionsList == null
                    || !exclusionsList.contains(field.getAnnotation(ExcelEntity.class).name()))) {
        boo = false;
    }
    return boo;
}

From source file:com.alfresco.orm.ORMUtil.java

public static Map<QName, Serializable> getAlfrescoProperty(final AlfrescoORM alfrescoORM)
        throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchMethodException,
        InvocationTargetException, InstantiationException {
    List<Field> fields = new ArrayList<Field>();
    ReflectionUtil.getFields(alfrescoORM.getClass(), fields);
    Map<QName, Serializable> retVal = new HashMap<QName, Serializable>(fields.size());
    for (Field field : fields) {
        if (!field.isAnnotationPresent(SetProperty.class)) {
            if (field.isAnnotationPresent(AlfrescoQName.class)
                    && !field.isAnnotationPresent(AlfrescoAssociation.class)) {
                AlfrescoQName alfrescoQName = field.getAnnotation(AlfrescoQName.class);
                QName qName = QName.createQName(alfrescoQName.namespaceURI(), alfrescoQName.localName());
                Method getterMethod = ReflectionUtil.getMethod(alfrescoORM.getClass(), field.getName());
                retVal.put(qName, (Serializable) getterMethod.invoke(alfrescoORM));
            } else if (field.isAnnotationPresent(AlfrescoAspect.class)) {
                Method getterMethod = ReflectionUtil.getMethod(alfrescoORM.getClass(), field.getName());
                AlfrescoORM aspect = (AlfrescoORM) getterMethod.invoke(alfrescoORM);
                if (null != aspect) {
                    retVal.putAll(getAlfrescoProperty(aspect));
                }/* w w w . j a va 2  s  .  c o  m*/
            }
        }
    }
    return retVal;
}

From source file:ambroafb.general.AnnotiationUtils.java

private static boolean checkValidationForContentTreeItemAnnotation(Field field, Object currSceneController,
        EditorPanel.EDITOR_BUTTON_TYPE type) {
    boolean contentIsCorrect = false;
    Annotations.ContentTreeItem annotation = field.getAnnotation(Annotations.ContentTreeItem.class);
    Object[] typeAndContent = getNodesTypeAndContent(field, currSceneController);
    String content = (String) typeAndContent[1];

    if (content.length() != Integer.parseInt(annotation.valueForLength())) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0],
                annotation.explainForLength() + annotation.valueForLength());
    } else if (!Pattern.matches(annotation.valueForSyntax(), content)) {
        changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForSyntax());
    } else {/*from w ww. j  a v  a2 s.c  om*/
        EditorPanelable newPanelableObject = (EditorPanelable) getInvokedClassMethod(
                currSceneController.getClass(), "getNewEditorPanelable", null, currSceneController);
        Object contr = getInvokedClassMethod(currSceneController.getClass(), "getOwnerController", null,
                currSceneController);
        // already exist this item for this code:
        if ((Boolean) getInvokedClassMethod(contr.getClass(), "accountAlreadyExistForCode",
                new Class[] { EditorPanelable.class, EditorPanel.EDITOR_BUTTON_TYPE.class }, contr,
                newPanelableObject, type)) {
            changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForExists());
        }
        // item has not a parent:
        else if (!(Boolean) getInvokedClassMethod(contr.getClass(), "accountHasParent",
                new Class[] { String.class }, contr, content)) {
            changeNodeTitleLabelVisual((Node) typeAndContent[0], annotation.explainForHasNotParent());
        } else {
            changeNodeTitleLabelVisual((Node) typeAndContent[0], "");
            contentIsCorrect = true;
        }
    }
    return contentIsCorrect;
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 * @param embeddedType//w  ww.  j a  v  a  2  s  . co m
 * @return the column mapping of the {@link java.reflect.Field} annotated with
 * {@link javax.persistence.EmbeddedId}.
 *
 * @see http://docs.oracle.com/javaee/6/api/index.html?javax/persistence/EmbeddedId.html
 */
public static <T> List<String> getCompoundKeyColumnNames(Class<T> embeddedType) {
    Preconditions.checkNotNull(embeddedType);
    List<String> columns = Lists.newArrayList();
    for (Field embeddedField : embeddedType.getDeclaredFields()) {
        javax.persistence.Column c = embeddedField.getAnnotation(javax.persistence.Column.class);
        if (c == null) {
            continue;
        }
        String normalizedName = normalizeCqlElementName(c.name());
        if (columns.contains(normalizedName)) {
            throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName));
        }
        columns.add(normalizedName);
    }
    for (Method embeddedMethod : embeddedType.getDeclaredMethods()) {
        javax.persistence.Column c = embeddedMethod.getAnnotation(javax.persistence.Column.class);
        if (c == null) {
            continue;
        }
        String normalizedName = normalizeCqlElementName(c.name());
        if (columns.contains(normalizedName)) {
            throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName));
        }
        columns.add(normalizedName);
    }
    return columns;
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 * @param primaryKeyField/*from  www  .  j  a  v  a 2  s  .co m*/
 * @return the column mapping to the {@link java.reflect.Field} annotated
 * with {@link javax.persistence.Id} and {@link javax.persistence.Column}
 *
 * @see http://docs.oracle.com/javaee/6/api/index.html?javax/persistence/Id.html
 */
public static String getPrimaryKeyColumnName(Field primaryKeyField) {
    Preconditions.checkNotNull(primaryKeyField);
    javax.persistence.Column column = primaryKeyField.getAnnotation(javax.persistence.Column.class);
    if (column == null) {
        /*
         * The documentation for @Id states that <quote>If no Column
         * annotation is specified, the primary key column name is assumed
         * to be the name of the primary key property or field.</quote>
         */
        return primaryKeyField.getName();
    } else {
        return normalizeCqlElementName(column.name());
    }
}

From source file:com.crowsofwar.gorecore.config.ConfigLoader.java

public static void save(Object obj, String path) {
    try {//from   w ww  .j a  v  a2s .  c o m

        Map<String, Object> map = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.getAnnotation(Load.class) != null) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        }

        ConfigLoader loader = new ConfigLoader(path, obj, map, false);
        loader.usedValues.putAll(map);
        loader.save();

    } catch (Exception e) {
        GoreCore.LOGGER.error("Error saving config @ " + path, e);
    }
}