Example usage for java.lang.reflect Field getAnnotations

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

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:com.dalaran.annotation.FieldMerge.java

public boolean merge(Activity a) {
    Field[] declaredFields = a.getClass().getDeclaredFields();
    boolean valid = false;
    for (Field field : declaredFields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(ViewById.class)) {
                boolean b = checkToMerge(a, field, (ViewById) annotation);
                if (b) {
                    valid = b;//www .  j  a v a 2  s  .co  m
                }
            }
        }
        Click annotation = field.getAnnotation(Click.class);
        if (annotation != null) {
            clickAnnotation(annotation, field, a);

        }
    }
    return valid;
}

From source file:gDao.genericDao.SimpleDaoHandler.java

private void injectGDao(Object bean) throws Exception {
    Class<? extends Object> beanClass;
    if (bean instanceof Advised) {
        Advised advisedServiceBean = (Advised) bean;
        bean = advisedServiceBean.getTargetSource().getTarget();
        beanClass = bean.getClass();/*from   w  w w .  java  2  s  .  c o  m*/
    } else
        beanClass = bean.getClass();

    Field[] fields = beanClass.getDeclaredFields();
    List<SimpleAnnotatedField> simpleDaoAnnotatedFieldList = new ArrayList<SimpleAnnotatedField>();
    for (Field field : fields) {
        Annotation[] annotations = field.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof SimpleDao) {
                simpleDaoAnnotatedFieldList
                        .add(new SimpleAnnotatedField(field, ((SimpleDao) annotation).value()));
            }
        }

    }

    if (simpleDaoAnnotatedFieldList.size() != 0) {
        for (SimpleAnnotatedField annotatedField : simpleDaoAnnotatedFieldList) {
            Field field = annotatedField.getAnnotatedField();
            field.setAccessible(true);
            GDao copyOfGDao = (GDao) BeanUtils.cloneBean(gDao);
            //                ProxyFactory proxyFactory = new ProxyFactory();
            //                factory.
            //                factory.addAdvisors(advisedGDao.getAdvisors());
            copyOfGDao.setPersistentClass(annotatedField.getPersistentClass());
            field.set(bean, copyOfGDao);
        }

    }
}

From source file:io.wcm.tooling.netbeans.sightly.completion.classLookup.RequestAttributeResolver.java

private Set<String> getAttributesFromClassLoader(String clazzname) {
    final Set<String> ret = new LinkedHashSet<>();
    try {/*from  www  .j a  va  2s . c om*/
        Class clazz = classPath.getClassLoader(true).loadClass(clazzname);
        for (Method method : clazz.getDeclaredMethods()) {
            for (Annotation annotation : method.getAnnotations()) {
                if (annotation.annotationType().getName().equals(REQUEST_ATTRIBUTE_CLASSNAME)) {
                    ret.add(method.getName());
                }
            }
        }
        for (Field field : clazz.getDeclaredFields()) {
            for (Annotation annotation : field.getAnnotations()) {
                if (annotation.annotationType().getName().equals(REQUEST_ATTRIBUTE_CLASSNAME)) {
                    ret.add(field.getName());
                }
            }
        }
    } catch (ClassNotFoundException cnfe) {
        LOGGER.log(Level.FINE, "Could not resolve class " + clazzname, cnfe);
    }
    return ret;
}

From source file:org.apache.hadoop.metrics2.lib.MetricsSourceBuilder.java

private void add(Object source, Field field) {
    for (Annotation annotation : field.getAnnotations()) {
        if (!(annotation instanceof Metric))
            continue;
        try {/*from  w w w .  jav  a 2 s.com*/
            // skip fields already set
            field.setAccessible(true);
            if (field.get(source) != null)
                continue;
        } catch (Exception e) {
            LOG.warn("Error accessing field " + field + " annotated with" + annotation, e);
            continue;
        }
        MutableMetric mutable = factory.newForField(field, (Metric) annotation, registry);
        if (mutable != null) {
            try {
                field.set(source, mutable);
                hasAtMetric = true;
            } catch (Exception e) {
                throw new MetricsException("Error setting field " + field + " annotated with " + annotation, e);
            }
        }
    }
}

From source file:org.eclipse.scanning.points.validation.ScanRequestValidator.java

private void validateAnnotations(Map<String, Object> dmodels)
        throws ValidationException, IllegalArgumentException, IllegalAccessException, ScanningException {

    for (String name : dmodels.keySet()) {

        // The model we will validate
        Object model = dmodels.get(name);

        // If the model has an annotated field which points at 
        // a detector, that detector must be in the scan.
        Field[] fields = model.getClass().getDeclaredFields();

        BeanMap beanMap = null; // May need to use newer version of BeanMap in Java9 if it uses setAccessable(true)
        for (Field field : fields) {
            Annotation[] anots = field.getAnnotations();
            for (Annotation annotation : anots) {
                if (annotation instanceof FieldDescriptor) {

                    FieldDescriptor des = (FieldDescriptor) annotation;
                    if (des.device() == DeviceType.RUNNABLE) { // Then its value must be in the devices.

                        if (beanMap == null)
                            beanMap = new BeanMap(model);
                        String reference = beanMap.get(field.getName()).toString();
                        if (!dmodels.containsKey(reference)) {
                            IRunnableDeviceService dservice = ValidatorService.getRunnableDeviceService();
                            if (dservice != null && dservice.getRunnableDevice(reference) != null) {
                                continue;
                            }//from w  ww. j a  v a 2s.  c  o m
                            String label = des.label() != null && des.label().length() > 0 ? des.label()
                                    : field.getName();
                            throw new ModelValidationException("The value of '" + label
                                    + "' references a device (" + reference + ") not a valid device!", model,
                                    field.getName());
                        }
                    }
                }
            }
        }
    }
}

From source file:org.pmp.budgeto.app.SwaggerDispatcherConfigTest.java

@Test
public void springConf() throws Exception {

    Class<?> clazz = swaggerDispatcherConfig.getClass();
    Assertions.assertThat(clazz.getAnnotations()).hasSize(4);
    Assertions.assertThat(clazz.isAnnotationPresent(Configuration.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableWebMvc.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableSwagger.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(ComponentScan.class)).isTrue();
    Assertions.assertThat(clazz.getAnnotation(ComponentScan.class).basePackages())
            .containsExactly("com.ak.swaggerspringmvc.shared.app", "com.ak.spring3.music");

    Field fSpringSwaggerConfig = clazz.getDeclaredField("springSwaggerConfig");
    Assertions.assertThat(fSpringSwaggerConfig.getAnnotations()).hasSize(1);
    Assertions.assertThat(fSpringSwaggerConfig.isAnnotationPresent(Autowired.class)).isTrue();

    Method mCustomImplementation = clazz.getDeclaredMethod("customImplementation", new Class[] {});
    Assertions.assertThat(mCustomImplementation.getAnnotations()).hasSize(1);
    Assertions.assertThat(mCustomImplementation.getAnnotation(Bean.class)).isNotNull();
}

From source file:org.livespark.formmodeler.renderer.backend.service.impl.Model2FormTransformerServiceImpl.java

protected Set<FieldSetting> getClassFieldSettings(Class clazz) {
    TreeSet<FieldSetting> settings = new TreeSet<FieldSetting>();
    for (Field field : clazz.getDeclaredFields()) {
        for (Annotation annotation : field.getAnnotations()) {
            if (annotation instanceof FieldDef) {
                FieldDef fieldDef = (FieldDef) annotation;
                Class fieldType = getFieldType(field, fieldDef);

                Class realType = fieldType;

                if (field.getGenericType() instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
                    Type paramArg = parameterizedType.getActualTypeArguments()[0];
                    realType = (Class) paramArg;
                }//w w  w .  j a  v a2  s. com

                FieldSetting setting = new FieldSetting(
                        field.getName(), new DefaultFieldTypeInfo(realType.getName(),
                                fieldType.isAssignableFrom(List.class), fieldType.isEnum()),
                        realType, fieldDef, field.getAnnotations());

                settings.add(setting);
            }
        }
    }
    if (clazz.getSuperclass() != null) {
        settings.addAll(getClassFieldSettings(clazz.getSuperclass()));
    }
    return settings;
}

From source file:org.eclipse.php.composer.api.entities.JsonEntity.java

protected String getFieldName(Field field) {
    String name = field.getName();
    for (Annotation anno : field.getAnnotations()) {
        if (anno.annotationType() == Name.class) {
            name = ((Name) anno).value();
        }//from  ww  w.  j a va2 s . co  m
    }
    return name;
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.property.field.FieldPropertyResolver.java

/**
 * Processes a property.//from  w w w.ja  v  a 2s . c o  m
 * 
 * @param entityType
 *            The entity type.
 * @param methods
 *            The method list.
 * @param field
 *            The property field.
 * @param <P>
 *            The property type.
 * @return The property.
 */
private <P> DescribedProperty<P> processProperty(final DescribedEntity<?> entityType,
        final List<Method> methods, final Field field) {
    final PropertyBuilder<P> builder = AbstractProperty.createBuilder();
    for (final Annotation a : field.getAnnotations()) {
        builder.addAnnotation(a);
    }
    final PropertyMatcher<Field> matcher = this.getFieldMatcherResolver();
    @SuppressWarnings("unchecked")
    // About as sure as we can get.
    final Class<P> type = (Class<P>) matcher.extractType(field);
    final String name = matcher.extractName(field);
    builder.raw(field).genericType(matcher.extractGenericType(field));
    builder.name(name).type(type).entityType(entityType);
    this.resolveAccessor(methods, builder, type, name);
    this.resolveMutator(methods, builder, type, name);
    return builder.buildDescribed();
}

From source file:org.lunarray.model.descriptor.builder.annotation.resolver.property.accessor.AccessorPropertyResolver.java

/**
 * Process the property.//from www . ja v  a2 s  .c  o  m
 * 
 * @param entityType
 *            The entity type.
 * @param methods
 *            The methods.
 * @param fields
 *            The fields.
 * @param method
 *            The accessor method.
 * @param <P>
 *            The property type.
 * @return The property.
 */
private <P> DescribedProperty<P> processProperty(final DescribedEntity<?> entityType,
        final List<Method> methods, final List<Field> fields, final Method method) {
    final PropertyBuilder<P> builder = AbstractProperty.createBuilder();
    for (final Annotation a : method.getAnnotations()) {
        builder.addAnnotation(a);
    }
    final PropertyMatcher<Method> resolver = this.getAccessorMatcherResolver();
    @SuppressWarnings("unchecked")
    // About as sure as we can get.
    final Class<P> type = (Class<P>) resolver.extractType(method);
    builder.accessor(method).genericType(resolver.extractGenericType(method));
    final String name = resolver.extractName(method);
    builder.name(name).type(type).entityType(entityType);
    // Resolve field.
    for (final Field field : fields) {
        if (this.getFieldMatcherResolver().matches(field, name, type)) {
            for (final Annotation a : field.getAnnotations()) {
                builder.addAnnotation(a);
            }
            builder.raw(field);
        }
    }
    // Resolve mutator.
    Method mutator = null;
    for (final Method mutatorCandidate : methods) {
        if (this.getMutatorMatcherResolver().matches(mutatorCandidate, name, type)) {
            for (final Annotation a : mutatorCandidate.getAnnotations()) {
                builder.addAnnotation(a);
            }
            mutator = mutatorCandidate;
        }
    }
    if (CheckUtil.isNull(mutator)) {
        builder.addModifier(Modifier.FINAL);
    } else {
        builder.mutator(mutator);
    }
    return builder.buildDescribed();
}