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:py.una.pol.karaku.util.UniqueHelper.java

private Map<String, UniqueRestrintion> getConstrains(final Class<?> clazz) {

    // TODO esto se crea cada vez que surge una excepcin, considerar la
    // posibilidad de guardarlo y utilizarlo mas tarde.
    Map<String, UniqueRestrintion> restrintions = new HashMap<String, UniqueRestrintion>();
    for (Field f : clazz.getDeclaredFields()) {
        Unique uniqueName = f.getAnnotation(Unique.class);
        if (uniqueName != null) {
            for (String fieldConstraint : uniqueName.value()) {
                UniqueRestrintion restrintion = restrintions.get(fieldConstraint);
                if (restrintion == null) {
                    restrintion = new UniqueRestrintion(fieldConstraint);
                    restrintions.put(fieldConstraint, restrintion);
                }//from  ww  w  . j ava2  s  .c  o m
                restrintion.addField(f.getName());
            }
        }
    }

    return restrintions;
}

From source file:com.cassius.spring.assembly.test.common.process.InjectIntoProcessor.java

/**
 * Do process before./*  www . j a  va2s. co  m*/
 *
 * @param context the context
 * @param instance the instance
 * @param field the field
 * @throws Exception the exception
 */
@Override
protected void doProcessBefore(ApplicationContext context, Object instance, Field field) throws Exception {
    Object fieldValue = FieldReader.newInstance(instance, field).read();
    InjectInto injectInto = field.getAnnotation(InjectInto.class);
    String[] targets = injectInto.value();
    for (String target : targets) {
        Object targetFieldValue = FieldReader.newInstance(instance, target).read();
        FieldWriter.newInstance(targetFieldValue, field.getName(), fieldValue).write();
    }
}

From source file:management.limbr.ui.entity.EntityListViewImpl.java

@PostConstruct
@SuppressWarnings("unchecked")
public void init() {
    grid = new Grid();
    grid.setEditorEnabled(true);/*from w w  w. j a v  a  2  s .  co m*/
    grid.setSizeFull();
    TextField filter = new TextField();
    filter.setInputPrompt(messages.get("filterLabel"));
    filter.addTextChangeListener(event -> listEntities(event.getText()));

    Button addNewButton = new Button(messages.get("newButtonLabel"), FontAwesome.PLUS);
    HorizontalLayout actions = new HorizontalLayout(filter, addNewButton);
    actions.setSpacing(true);
    grid.removeAllColumns();

    java.lang.reflect.Field[] fields = entityClass.getDeclaredFields();
    for (java.lang.reflect.Field field : fields) {
        if (null != field.getAnnotation(ListColumn.class)) {
            grid.addColumn(field.getName());
        }
    }

    Grid.Column editColumn = grid.addColumn(EDIT_PROPERTY_ID);
    editColumn.setMaximumWidth(50.0);
    editColumn.setHeaderCaption("");
    editColumn.setRenderer(new ButtonRenderer(
            event -> listeners.forEach(listener -> listener.editItemClicked((T) event.getItemId()))));

    addNewButton.addClickListener(event -> listeners.forEach(EntityListView.Listener::addNewClicked));

    addComponent(actions);
    addComponent(grid);

    listeners.forEach(listener -> listener.viewInitialized(this));

    refresh();
}

From source file:be.bittich.dynaorm.maping.BasicColumnMapping.java

@Override
public <T> Map<String, Field> mapToSQLColumns(T obj, TableColumn tableColumn) {
    //get the fields from the object
    Field[] fields = obj.getClass().getDeclaredFields();
    Set<String> columnsFromDB = tableColumn.getColumns().keySet();
    //map the column name with the field
    Map<String, Field> filteredFields = new HashMap();
    for (Field field : fields) {
        field.setAccessible(true);/*ww  w. j a  v  a 2 s .c  o  m*/
        MetaColumn annotationX = field.getAnnotation(MetaColumn.class);
        //by default, columnName=field name
        String columnName = field.getName();
        if (annotationX != null && !isEmpty(annotationX.columnName())) {
            columnName = annotationX.columnName();
        }
        //map only the field present in the table
        if (columnsFromDB.contains(columnName)) {
            filteredFields.put(columnName, field);
        }
    }

    return filteredFields;
}

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

/**
 * Creates a new {@link DynamoDBHashAndRangeKeyMethodExtractor} for the given domain type.
 *
 * @param idType/*from w  w  w .j  a  va  2 s  .  c  om*/
 *            must not be {@literal null}.
 */
public DynamoDBHashAndRangeKeyMethodExtractorImpl(final Class<T> idType) {

    Assert.notNull(idType, "Id type must not be null!");
    this.idType = idType;
    ReflectionUtils.doWithMethods(idType, new MethodCallback() {
        @Override
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBHashKey.class) != null) {
                Assert.isNull(hashKeyMethod,
                        "Multiple methods annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
                ReflectionUtils.makeAccessible(method);
                hashKeyMethod = method;
            }
        }
    });
    ReflectionUtils.doWithFields(idType, new FieldCallback() {
        @Override
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBHashKey.class) != null) {
                Assert.isNull(hashKeyField,
                        "Multiple fields annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
                ReflectionUtils.makeAccessible(field);

                hashKeyField = field;
            }
        }
    });
    ReflectionUtils.doWithMethods(idType, new MethodCallback() {
        @Override
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBRangeKey.class) != null) {
                Assert.isNull(rangeKeyMethod, "Multiple methods annotated by @DynamoDBRangeKey within type "
                        + idType.getName() + "!");
                ReflectionUtils.makeAccessible(method);
                rangeKeyMethod = method;
            }
        }
    });
    ReflectionUtils.doWithFields(idType, new FieldCallback() {
        @Override
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBRangeKey.class) != null) {
                Assert.isNull(rangeKeyField,
                        "Multiple fields annotated by @DynamoDBRangeKey within type " + idType.getName() + "!");
                ReflectionUtils.makeAccessible(field);
                rangeKeyField = field;
            }
        }
    });
    if (hashKeyMethod == null && hashKeyField == null) {
        throw new IllegalArgumentException(
                "No method or field annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
    }
    if (rangeKeyMethod == null && rangeKeyField == null) {
        throw new IllegalArgumentException(
                "No method or field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!");
    }
    if (hashKeyMethod != null && hashKeyField != null) {
        throw new IllegalArgumentException(
                "Both method and field annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
    }
    if (rangeKeyMethod != null && rangeKeyField != null) {
        throw new IllegalArgumentException(
                "Both method and field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!");
    }
}

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

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

    ValidValueType validValueType = field.getAnnotation(ValidValueType.class);
    if (validValueType != null) {
        try {//from  www .j  a v a 2 s . co m
            String value = BeanUtils.getProperty(dataObject, field.getName());
            //Note: null values are checked by a separate rule so null should be valid
            if (value != null) {
                Set<String> validValueSet = new HashSet<>();
                Service serviceProxy = ServiceProxyFactory.getServiceProxy();
                if (validValueType.lookupClass().length > 0) {
                    for (Class lookupClass : validValueType.lookupClass()) {
                        List<LookupEntity> lookups = serviceProxy.getLookupService().findLookup(lookupClass);
                        lookups.forEach(item -> {
                            validValueSet.add(item.getCode());
                        });
                    }
                }
                validValueSet.addAll(Arrays.asList(validValueType.value()));
                if (validValueType.enumClass().length > 0) {
                    for (Class enumClass : validValueType.enumClass()) {
                        Object enumValues[] = enumClass.getEnumConstants();
                        if (enumValues != null) {
                            for (Object enumValue : enumValues) {
                                validValueSet.add(enumValue.toString());
                            }
                        }
                    }
                }

                if (validValueSet.contains(value) == false) {
                    valid = false;
                }
            }
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
            throw new OpenStorefrontRuntimeException("Unexpected error occur trying to get value from object.",
                    ex);
        }
    }
    return valid;
}

From source file:gemlite.core.util.CommandBase.java

public void parse() {
    cmdFields = new TreeSet<CmdField>();
    for (Class c = getClass(); c != null; c = c.getSuperclass()) {
        for (Field f : c.getDeclaredFields()) {
            Option o = f.getAnnotation(Option.class);
            if (o != null) {
                CmdField cf = new CmdField();
                cf.field = f;//from   w  w  w  .j  av  a2 s .  co  m
                cf.option = o;
                cmdFields.add(cf);
            }
        }
    }
}

From source file:de.systemoutprintln.util.logging.spring.LogPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {

        @Override//from w w w  .  j av a  2s.  c  o  m
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.getAnnotation(Log.class) != null) {
                Logger logger = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, logger);
            }
        }
    });

    return bean;
}

From source file:org.jsonschema2pojo.integration.config.AnnotationStyleIT.java

@Test
public void annotationStyleJackson2ProducesJsonPropertyDescription() throws Exception {
    Class<?> generatedType = schemaRule.generateAndCompile("/schema/description/description.json",
            "com.example", config("annotationStyle", "jackson2")).loadClass("com.example.Description");

    Field field = generatedType.getDeclaredField("description");
    assertThat(field.getAnnotation(JsonPropertyDescription.class).value(),
            is("A description for this property"));
}

From source file:com.epam.ta.reportportal.database.ActivityDocumentHandler.java

private String getDbRepresentation(Field field) {
    return field.isAnnotationPresent(org.springframework.data.mongodb.core.mapping.Field.class)
            ? field.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class).value()
            : field.getName();/* w  w w  . j  a va2 s.  c  om*/
}