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:es.logongas.ix3.util.ReflectionUtil.java

static private <T extends Annotation> T getFieldAnnotation(Class baseClass, String propertyName,
        Class<T> annotationClass) {
    Field field = getField(baseClass, propertyName);
    if (field == null) {

        return null;
    }/*from   w w  w .j a v  a 2 s  .  c o  m*/

    T annotation = field.getAnnotation(annotationClass);

    return annotation;
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

/**
 * Get a field name (object attribute name) or the value of @Name if
 * annotation is present. In other words, if @Name is present returns
 * field.getAnnotation(Name.class).value(), otherwise field.getName();
 * /*from w w  w . j  a va2  s. c  o m*/
 * @param field
 * @return @Name annotation value or object attribute name;
 */
public static String getFieldName(Field field) {
    if (field.isAnnotationPresent(Name.class)) {
        String name = field.getAnnotation(Name.class).value();
        if (name == null || name.trim().isEmpty())
            throw new EntryException("Annotation @Name must have a value");
        return name;
    } else
        return field.getName();
}

From source file:com.evolveum.midpoint.prism.xjc.PrismForJAXBUtil.java

private static <T> Field getAnyField(Class<T> clazz) {
    for (Field field : clazz.getDeclaredFields()) {
        XmlAnyElement xmlAnyElementAnnotation = field.getAnnotation(XmlAnyElement.class);
        if (xmlAnyElementAnnotation != null) {
            return field;
        }/* w ww  .  j  a  v a  2  s. c  o  m*/
    }
    return null;
}

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

/**
 * Constructs a map of {@link String}S representing column names to {@link
 * Field}S./*from  w ww.j  a va  2 s  .c  o m*/
 *
 * @param entityClazz
 * @return
 */
public static <T> Map<String, AttributeAccessor> createAccessors(Class<T> entityClazz) {
    Preconditions.checkNotNull(entityClazz);
    Map<String, AttributeAccessor> map = Maps.newLinkedHashMap();
    for (Field f : entityClazz.getDeclaredFields()) {
        javax.persistence.Column c = f.getAnnotation(javax.persistence.Column.class);
        if (c == null) {
            continue;
        }
        String normalizedName = normalizeCqlElementName(c.name());
        if (map.containsKey(normalizedName)) {
            throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName));
        }
        AttributeAccessor accessor = new AttributeAccessorFieldIntrospection(f);
        map.put(normalizedName, accessor);
    }
    for (Method firstMethod : entityClazz.getDeclaredMethods()) {
        javax.persistence.Column c = firstMethod.getAnnotation(javax.persistence.Column.class);
        if (c == null) {
            continue;
        }
        String normalizedName = normalizeCqlElementName(c.name());
        /*
         * For bean getters and setters, we allow to annotate either the
         * getter or the setter and will find the corresponding counterpart.
         * If the column name is already mapped, then there's either a
         * @Column-annotated field, or the previous reversed pair of getters
         * and setters was found. Either way, ignore this annotated method.
         */
        if (map.containsKey(normalizedName)) {
            continue;
        }
        String firstMethodName = firstMethod.getName();
        AttributeAccessor accessor = null;

        if (firstMethodName.startsWith("set")) {
            String attributeName = firstMethodName.substring(NON_BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH);
            Method secondMethod = findGetterMethod(entityClazz, attributeName);
            if (secondMethod == null) {
                throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName));
            }
            accessor = new AttributeAccessorBeanMethods(secondMethod, firstMethod);
        } else if (firstMethodName.startsWith("is")) {
            String attributeName = firstMethodName.substring(BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH);
            Method secondMethod = findSetterMethod(entityClazz, attributeName);
            if (secondMethod == null) {
                throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName));
            }
            accessor = new AttributeAccessorBeanMethods(firstMethod, secondMethod);
        } else if (firstMethodName.startsWith("get")) {
            String attributeName = firstMethodName.substring(NON_BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH);
            /*
             * Find the corresponding setter.
             */
            Method secondMethod = findSetterMethod(entityClazz, attributeName);
            if (secondMethod == null) {
                throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName));
            }
            accessor = new AttributeAccessorBeanMethods(firstMethod, secondMethod);
        }
        map.put(normalizedName, accessor);
    }

    return map;
}

From source file:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleProperties(Class<?> classz, StringBuilder sb, Map<String, String> declarations,
        String uriPrefix) {//from   w w  w  . jav  a  2s  .c om
    boolean result = false;
    String prepend = "";
    Set<String> processedFields = new HashSet<String>();
    sb.append("{");
    for (Field field : classz.getFields()) {
        JsonSchemaProperty propertyDecl = field.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null) {
            Class<?> propClassz = field.getType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    for (Method method : classz.getMethods()) {
        JsonSchemaProperty propertyDecl = method.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null && !processedFields.contains(propertyDecl.name())) {
            Class<?> propClassz = method.getReturnType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    sb.append("}");
    return result;
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static boolean fkIsNullable(Field field) {
    if (field.isAnnotationPresent(ManyToOne.class) && !field.getAnnotation(ManyToOne.class).optional()) {
        return false;
    }//from w w w .  j a  v a2s . c o m
    if (field.isAnnotationPresent(JoinColumn.class) && !field.getAnnotation(JoinColumn.class).nullable()) {
        return false;
    }
    if (field.isAnnotationPresent(OneToMany.class)) {
        String mappedBy = field.getAnnotation(OneToMany.class).mappedBy();
        if (StringUtils.isNotEmpty(mappedBy)) {
            try {
                Class targetEntity = MappingUtils.determineTargetEntity(field);
                Field fkField = targetEntity.getDeclaredField(mappedBy);
                if (fkField.isAnnotationPresent(JoinColumn.class)
                        && !fkField.getAnnotation(JoinColumn.class).nullable()) {
                    return false;
                }
            } catch (NoSuchFieldException e) {
                LOG.error("unable to get mappedBy field", e);
            }
        }
    }
    return true;
}

From source file:com.l2jfree.util.Introspection.java

private static boolean writeFields(Class<?> c, Object accessor, StringBuilder dest, String eol, boolean init) {
    if (c == null)
        throw new IllegalArgumentException("No class specified.");
    else if (!c.isInstance(accessor))
        throw new IllegalArgumentException(accessor + " is not a " + c.getCanonicalName());
    for (Field f : c.getDeclaredFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod))
            continue;
        if (init)
            init = false;/*from   w w w . j a  v a 2  s  .  co  m*/
        else if (eol == null)
            dest.append(", ");
        String fieldName = null;
        final Column column = f.getAnnotation(Column.class);
        if (column != null)
            fieldName = column.name();
        if (StringUtils.isEmpty(fieldName))
            fieldName = f.getName();
        dest.append(fieldName);
        dest.append(" = ");
        try {
            f.setAccessible(true);
            Object val = f.get(accessor);
            if (accessor == val)
                dest.append("this");
            else
                deepToString(val, dest, null);
        } catch (Exception e) {
            dest.append("???");
        } finally {
            try {
                f.setAccessible(false);
            } catch (Exception e) {
                // ignore
            }
        }
        if (eol != null)
            dest.append(eol);
    }
    return !init;
}

From source file:ch.rasc.extclassgenerator.association.AbstractAssociation.java

public static AbstractAssociation createAssociation(ModelAssociation associationAnnotation, ModelBean model,
        Class<?> typeOfFieldOrReturnValue, Class<?> declaringClass, String name) {
    ModelAssociationType type = associationAnnotation.value();

    Class<?> associationClass = associationAnnotation.model();
    if (associationClass == Object.class) {
        associationClass = typeOfFieldOrReturnValue;
    }/*from w  w w . j  a v a  2s  .c o m*/

    final AbstractAssociation association;

    if (type == ModelAssociationType.HAS_MANY) {
        association = new HasManyAssociation(associationClass);
    } else if (type == ModelAssociationType.BELONGS_TO) {
        association = new BelongsToAssociation(associationClass);
    } else {
        association = new HasOneAssociation(associationClass);
    }

    association.setAssociationKey(name);

    if (StringUtils.hasText(associationAnnotation.foreignKey())) {
        association.setForeignKey(associationAnnotation.foreignKey());
    } else if (type == ModelAssociationType.HAS_MANY) {
        association.setForeignKey(StringUtils.uncapitalize(declaringClass.getSimpleName()) + "_id");
    } else if (type == ModelAssociationType.BELONGS_TO || type == ModelAssociationType.HAS_ONE) {
        association.setForeignKey(name + "_id");
    }

    if (StringUtils.hasText(associationAnnotation.primaryKey())) {
        association.setPrimaryKey(associationAnnotation.primaryKey());
    } else if (type == ModelAssociationType.HAS_MANY && StringUtils.hasText(model.getIdProperty())
            && !model.getIdProperty().equals("id")) {
        association.setPrimaryKey(model.getIdProperty());
    } else if (type == ModelAssociationType.BELONGS_TO || type == ModelAssociationType.HAS_ONE) {
        Model associationModelAnnotation = associationClass.getAnnotation(Model.class);
        if (associationModelAnnotation != null && StringUtils.hasText(associationModelAnnotation.idProperty())
                && !associationModelAnnotation.idProperty().equals("id")) {
            association.setPrimaryKey(associationModelAnnotation.idProperty());
        }
        ReflectionUtils.doWithFields(associationClass, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (field.getAnnotation(ModelId.class) != null && !"id".equals(field.getName())) {
                    association.setPrimaryKey(field.getName());
                }
            }

        });
    }

    if (type == ModelAssociationType.HAS_MANY) {
        HasManyAssociation hasManyAssociation = (HasManyAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "setterName"));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "getterName"));
        }

        if (associationAnnotation.autoLoad()) {
            hasManyAssociation.setAutoLoad(Boolean.TRUE);
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            hasManyAssociation.setName(associationAnnotation.name());
        } else {
            hasManyAssociation.setName(name);
        }

    } else if (type == ModelAssociationType.BELONGS_TO) {
        BelongsToAssociation belongsToAssociation = (BelongsToAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            belongsToAssociation.setSetterName(associationAnnotation.setterName());
        } else {
            belongsToAssociation.setSetterName("set" + StringUtils.capitalize(name));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            belongsToAssociation.setGetterName(associationAnnotation.getterName());
        } else {
            belongsToAssociation.setGetterName("get" + StringUtils.capitalize(name));
        }

        if (associationAnnotation.autoLoad()) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "autoLoad"));
        }
        if (StringUtils.hasText(associationAnnotation.name())) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "name"));
        }
    } else {
        HasOneAssociation hasOneAssociation = (HasOneAssociation) association;

        if (StringUtils.hasText(associationAnnotation.setterName())) {
            hasOneAssociation.setSetterName(associationAnnotation.setterName());
        } else {
            hasOneAssociation.setSetterName("set" + StringUtils.capitalize(name));
        }

        if (StringUtils.hasText(associationAnnotation.getterName())) {
            hasOneAssociation.setGetterName(associationAnnotation.getterName());
        } else {
            hasOneAssociation.setGetterName("get" + StringUtils.capitalize(name));
        }

        if (associationAnnotation.autoLoad()) {
            LogFactory.getLog(ModelGenerator.class)
                    .warn(getWarningText(declaringClass, name, association.getType(), "autoLoad"));
        }

        if (StringUtils.hasText(associationAnnotation.name())) {
            hasOneAssociation.setName(associationAnnotation.name());
        }
    }

    if (StringUtils.hasText(associationAnnotation.instanceName())) {
        association.setInstanceName(associationAnnotation.instanceName());
    }

    return association;
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

/**
 *
 * @param emf//  www. j av a  2 s  .  co m
 * @return a map from the targetEntity of the OneToMany collection to the field of this collection descriptor
 * @throws Exception
 */
public static Map<Class, Set<Field>> getCollectionDescriptorReferences(EntityManagerFactory emf)
        throws Exception {
    Map<Class, Set<Field>> detailClassToMasterFields = new HashMap<Class, Set<Field>>();

    for (Class aClass : getEntityClasses(emf)) {
        for (Field field : getFielsWith(OneToMany.class, aClass)) {
            OneToMany a = field.getAnnotation(OneToMany.class);
            Class targetEntity = determineTargetEntity(field, a.targetEntity());
            if (StringUtils.isEmpty(a.mappedBy())) {
                Set<Field> fields = detailClassToMasterFields.get(targetEntity);
                if (fields == null) {
                    detailClassToMasterFields.put(targetEntity, fields = new HashSet<Field>());
                }
                fields.add(field);
            }
        }
    }

    return detailClassToMasterFields;
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Field f) {
    if (f.isAnnotationPresent(I18n.class)) {
        if (f.getAnnotation(I18n.class).value().length() > 0) {
            return f.getAnnotation(I18n.class).value();
        } else {//from www .j  a v  a2 s  . c  o m
            return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
        }
    }
    // else if(f.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = f.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
}