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:com.impetus.kundera.metadata.processor.relation.OneToManyRelationMetadataProcessor.java

@Override
public void addRelationIntoMetadata(Field relationField, EntityMetadata metadata) {

    OneToMany ann = relationField.getAnnotation(OneToMany.class);
    Class<?> targetEntity = PropertyAccessorHelper.getGenericClass(relationField);

    // now, check annotations
    if (null != ann.targetEntity() && !ann.targetEntity().getSimpleName().equals("void")) {
        targetEntity = ann.targetEntity();
    }/*from  w ww  .j  ava2s .  com*/

    Relation relation = new Relation(relationField, targetEntity, relationField.getType(), ann.fetch(),
            Arrays.asList(ann.cascade()), Boolean.TRUE, ann.mappedBy(), Relation.ForeignKey.ONE_TO_MANY);

    boolean isJoinedByFK = relationField.isAnnotationPresent(JoinColumn.class);

    if (isJoinedByFK) {
        JoinColumn joinColumnAnn = relationField.getAnnotation(JoinColumn.class);
        relation.setJoinColumnName(
                StringUtils.isBlank(joinColumnAnn.name()) ? relationField.getName() : joinColumnAnn.name());
    }

    else {
        String joinColumnName = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName();
        if (relation.getMappedBy() != null) {
            try {
                Field mappedField = metadata.getEntityClazz().getDeclaredField(relation.getMappedBy());
                if (mappedField != null && mappedField.isAnnotationPresent(JoinColumn.class)) {
                    joinColumnName = mappedField.getAnnotation(JoinColumn.class).name();
                }
            } catch (NoSuchFieldException e) {
                // do nothing, it means not a case of self association
            } catch (SecurityException e) {
                // do nothing, it means not a case of self association
            }
        }
        relation.setJoinColumnName(joinColumnName);
    }

    relation.setBiDirectionalField(metadata.getEntityClazz());
    metadata.addRelation(relationField.getName(), relation);
    metadata.setParent(true);
}

From source file:edu.usu.sdl.openstorefront.validation.UniqueRule.java

@Override
protected boolean validate(Field field, Object dataObject) {
    boolean valid = true;

    if (dataObject != null) {
        Unique unique = field.getAnnotation(Unique.class);
        if (unique != null) {
            try {
                String value = BeanUtils.getProperty(dataObject, field.getName());
                if (value != null) {
                    UniqueHandler handler = unique.value().newInstance();
                    valid = handler.isUnique(field, value);
                }/*ww w .  j  a  va2s  . c o  m*/
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException ex) {
                throw new OpenStorefrontRuntimeException("Unexpected error occur trying open the handler.", ex);
            }
        }
    }

    return valid;
}

From source file:org.apache.aries.blueprint.plugin.model.Bean.java

private Field getPersistenceUnit() {
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        PersistenceUnit persistenceUnit = field.getAnnotation(PersistenceUnit.class);
        if (persistenceUnit != null) {
            return field;
        }//from   ww w. j a va 2s  .  co m
    }
    return null;
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.FieldAndGetterReflectionEntityInformation.java

/**
 * Creates a new {@link FieldAndGetterReflectionEntityInformation} inspecting the
 * given domain class for a getter carrying the given annotation.
 * /*from  w w  w  .ja v a2s.  c  o  m*/
 * @param domainClass
 *            must not be {@literal null}.
 * @param annotation
 *            must not be {@literal null}.
 */
public FieldAndGetterReflectionEntityInformation(Class<T> domainClass,
        final Class<? extends Annotation> annotation) {

    super(domainClass);
    Assert.notNull(annotation);

    ReflectionUtils.doWithMethods(domainClass, new MethodCallback() {
        public void doWith(Method method) {
            if (method.getAnnotation(annotation) != null) {
                FieldAndGetterReflectionEntityInformation.this.method = method;
                return;
            }
        }
    });

    if (method == null) {
        ReflectionUtils.doWithFields(domainClass, new FieldCallback() {
            public void doWith(Field field) {
                if (field.getAnnotation(annotation) != null) {
                    FieldAndGetterReflectionEntityInformation.this.field = field;
                    return;
                }
            }
        });
    }

    Assert.isTrue(this.method != null || this.field != null,
            String.format("No field or method annotated with %s found!", annotation.toString()));
    Assert.isTrue(this.method == null || this.field == null,
            String.format("Both field and method annotated with %s found!", annotation.toString()));

    if (method != null) {
        ReflectionUtils.makeAccessible(method);
    }
}

From source file:Employee.java

 @PostConstruct
public void jndiInject(InvocationContext invocation) {
   Object target = invocation.getTarget();
   Field[] fields = target.getClass().getDeclaredFields();
   Method[] methods = target.getClass().getDeclaredMethods();

   // find all @JndiInjected fields methods and set them
   try {/*from   w ww  .j a  v a2  s .  c  o m*/
      InitialContext ctx = new InitialContext();
      for (Method method : methods) {
         JndiInjected inject = method.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            method.setAccessible(true);
            method.invoke(target, obj);
         }
      }
      for (Field field : fields) {
         JndiInjected inject = field.getAnnotation(JndiInjected.class);
         if (inject != null) {
            Object obj = ctx.lookup(inject.value());
            field.setAccessible(true);
            field.set(target, obj);
         }
      }
      invocation.proceed();
   } catch (Exception ex) {
      throw new EJBException("Failed to execute @JndiInjected", ex);
   }
}

From source file:com.epam.ta.reportportal.database.search.CriteriaMap.java

private String getSearchCriteria(Field f) {
    return f.getAnnotation(FilterCriteria.class).value();
}

From source file:com.chiorichan.database.SqlTable.java

protected Object toObject(Object clz, ResultSet rs) throws SQLException {
    Validate.notNull(clz);/*ww  w. j  a  v  a  2s.co m*/
    Validate.notNull(rs);

    if (rs.getRow() == 0)
        rs.first();

    for (Field f : clz.getClass().getDeclaredFields()) {
        SqlColumn sc = f.getAnnotation(SqlColumn.class);

        try {
            if (sc != null && rs.getObject(sc.name()) != null) {
                Object obj = rs.getObject(sc.name());
                if (f.getType().equals(String.class)) {
                    f.set(clz, ObjectUtil.castToString(obj));
                } else if (obj instanceof String && (f.getType().equals(Long.class)
                        || f.getType().getSimpleName().equalsIgnoreCase("long"))) {
                    f.set(clz, Long.parseLong((String) obj));
                } else if (obj instanceof String && (f.getType().equals(Integer.class)
                        || f.getType().getSimpleName().equalsIgnoreCase("int"))) {
                    f.set(clz, Integer.parseInt((String) obj));
                } else {
                    f.set(clz, obj);
                }
            }
        } catch (IllegalArgumentException e) {
            Loader.getLogger()
                    .severe("We can't cast the value '" + rs.getObject(sc.name()) + "' from column `"
                            + sc.name() + "` with type `" + rs.getObject(sc.name()).getClass().getSimpleName()
                            + "` to FIELD `" + f.getName() + "` with type `" + f.getType() + "`.");
        } catch (IllegalAccessException e) {
            Loader.getLogger().severe("We don't have access to FIELD `" + f.getName()
                    + "`, Be sure the field has a PUBLIC modifier.");
        }
    }

    return clz;
}

From source file:com.ryantenney.metrics.spring.InjectMetricAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    final Class<?> targetClass = AopUtils.getTargetClass(bean);

    ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
        @Override//from  w  w  w  . j a v  a2 s  .  c  o  m
        public void doWith(Field field) throws IllegalAccessException {
            final InjectMetric annotation = field.getAnnotation(InjectMetric.class);
            final String metricName = Util.forInjectMetricField(targetClass, field, annotation);

            final Class<?> type = field.getType();
            Metric metric = null;
            if (Meter.class == type) {
                metric = metrics.meter(metricName);
            } else if (Timer.class == type) {
                metric = metrics.timer(metricName);
            } else if (Counter.class == type) {
                metric = metrics.counter(metricName);
            } else if (Histogram.class == type) {
                metric = metrics.histogram(metricName);
            } else {
                throw new IllegalStateException("Cannot inject a metric of type " + type.getCanonicalName());
            }

            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, bean, metric);

            LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        }
    }, FILTER);

    return bean;
}

From source file:my.adam.smo.common.LoggerInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(InjectLogger.class) != null) {
                Logger logger = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, logger);
            }//from  www. j av a2  s . co  m
        }
    });

    return bean;
}