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:atunit.spring.SpringContainer.java

public Object createTest(Class<?> testClass, Map<Field, Object> fieldValues) throws Exception {

    GenericApplicationContext ctx = new GenericApplicationContext();

    for (Field field : fieldValues.keySet()) {

        Bean beanAnno = field.getAnnotation(Bean.class);

        AbstractBeanDefinition beandef = defineInstanceHolderFactoryBean(field.getType(),
                fieldValues.get(field));

        if ((beanAnno != null) && !beanAnno.value().equals("")) {
            ctx.registerBeanDefinition(beanAnno.value(), beandef);
        } else {/*  w w w .  java  2  s.c  om*/
            BeanDefinitionReaderUtils.registerWithGeneratedName(beandef, ctx);
        }
    }

    loadBeanDefinitions(testClass, ctx);

    fillInMissingFieldBeans(testClass, ctx);

    ctx.refresh();

    Object test = testClass.newInstance();
    for (Field field : testClass.getDeclaredFields()) {
        field.setAccessible(true);
        Bean beanAnno = field.getAnnotation(Bean.class);
        if (beanAnno == null) {
            if (fieldValues.containsKey(field)) {
                field.set(test, fieldValues.get(field));
            }
        } else {
            if (!beanAnno.value().equals("")) {
                field.set(test, ctx.getBean(beanAnno.value()));
            } else {
                String[] beanNames = ctx.getBeanNamesForType(field.getType());
                if (beanNames.length < 1) {
                    throw new BeanCreationException("There are no beans defined with type " + field.getType());
                }
                if (beanNames.length > 1) {
                    throw new BeanCreationException(
                            "There are " + beanNames.length + " beans defined with type " + field.getType()
                                    + "; consider wiring by name instead");
                }
                field.set(test, ctx.getBean(beanNames[0]));
            }
        }
    }

    return test;
}

From source file:com.db2eshop.governance.UIBinder.java

/**
 * <p>create.</p>/*from   w  w w.j  a  v  a  2s  . co  m*/
 *
 * @param entityClazz a {@link java.lang.Class} object.
 * @return a {@link java.util.Map} object.
 */
public Map<String, LabeledForm<?>> create(Class<? extends AbstractModel<?>> entityClazz) {
    Map<String, LabeledForm<?>> ui = new HashMap<String, LabeledForm<?>>();

    Field[] fields = entityClazz.getDeclaredFields();
    for (Field field : fields) {
        String fieldName = field.getName();
        if (field.getAnnotation(UIHide.class) != null) {
            continue;
        }
        UIBind uiBind = field.getAnnotation(UIBind.class);
        UIEmbedded uiEmbedded = field.getAnnotation(UIEmbedded.class);
        if (uiBind != null && uiEmbedded == null) {
            Class<? extends LabeledForm<?>> inputClazz = uiBind.value();
            if (inputClazz != null) {
                try {
                    LabeledForm<?> input = ClassUtil.newInstance(inputClazz);
                    input.setLabel(StringUtil.nominilize(fieldName));
                    ui.put(fieldName, input);
                } catch (RuntimeException e) {
                    log.error("Could not instantiate: " + inputClazz.getName(), e);
                }
            } else {
                log.error("No bound LabeledInput found on: " + entityClazz.getName() + "#" + fieldName);
            }
        } else if (uiBind == null && uiEmbedded != null) {
            Class<?> clazz = field.getType();
            if (!AbstractModel.class.isAssignableFrom(clazz)) {
                log.error("Property " + entityClazz.getName() + "#" + fieldName
                        + " is forced to be embedded entity but not assignable to AbstractModel. Skipping.");
            } else {
                AbstractDao<?> daoToBeSet = tableValueEntityResolver.getDao(clazz);
                EntityForm input = new EntityForm(daoToBeSet);
                input.setLabel(StringUtil.nominilize(fieldName));
                ui.put(fieldName, input);
            }
        } else {
            if (uiBind != null && uiEmbedded != null) {
                log.error("Property " + entityClazz.getName() + "#" + fieldName
                        + " is forced to be embedded and bound. Skipping.");
            } else {
                log.debug("Property " + entityClazz.getName() + "#" + fieldName + " not forced to be bound.");
            }
        }
    }
    return ui;
}

From source file:org.querybyexample.jpa.JpaUniqueUtil.java

private Field columnNameToField(Class<?> clazz, String columnName) {
    for (Field field : clazz.getFields()) {
        Column column = field.getAnnotation(Column.class);
        if (equalsIgnoreCase(columnName, column.name())) {
            return field;
        }//  w w w  .  j  a v  a2 s . c  om
    }
    return null;
}

From source file:org.cybercat.automation.core.PageFactoryImpl.java

@SuppressWarnings("unchecked")
public <T extends AbstractPageObject> T createPage(Class<T> page) throws PageObjectException {
    Constructor<T> cons;/*w  w w .j  a  va  2 s  . co  m*/
    try {
        cons = page.getConstructor();
        T result = cons.newInstance();
        for (Field field : page.getDeclaredFields()) {
            field.setAccessible(true);
            if (field.getAnnotation(CCProperty.class) != null) {
                AnnotationBuilder.processPropertyField(result, field);
            }
        }
        AspectJProxyFactory proxyFactory = new AspectJProxyFactory(result);
        proxyFactory.addAspect(new PageObjectStateControlAcpect(this));
        result = (T) proxyFactory.getProxy();
        return result;
    } catch (Exception e) {
        throw new PageObjectException("Page object creation problem.", e);
    }
}

From source file:pl.maciejwalkowiak.plist.FieldSerializer.java

private String createKey(Field field) {
    String keyToWrap;//from w w w . j a  va2 s  .  com

    if (field.isAnnotationPresent(PlistAlias.class)) {
        PlistAlias alias = field.getAnnotation(PlistAlias.class);

        if (alias.followStrategy()) {
            keyToWrap = plistSerializer.getNamingStrategy().fieldNameToKey(alias.value());
        } else {
            keyToWrap = alias.value();
        }
    } else {
        keyToWrap = plistSerializer.getNamingStrategy().fieldNameToKey(field.getName());
    }

    return XMLHelper.wrap(keyToWrap).with("key");
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static void printObjectProperties(final Logger log, final Object object,
        final boolean onlyImportantField) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                    if (null == value) {
                        value = "";
                    }//from w  w w  . ja  v  a2  s .c o m
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                } catch (IllegalAccessException e) {
                    System.out.println(e);
                }

                if (onlyImportantField) {
                    Annotation annotation = field.getAnnotation(ImportantField.class);
                    if (null == annotation) {
                        continue;
                    }
                }

                if (log != null) {
                    log.info(name + "=" + value);
                } else {
                    System.out.println(name + "=" + value);
                }
            }
        }
    }
}

From source file:org.jasig.cas.util.annotation.AbstractAnnotationBeanPostProcessor.java

public final Object postProcessBeforeInitialization(final Object bean, final String beanName)
        throws BeansException {

    final List<Field> fields = new ArrayList<Field>();
    final Class<?> clazz = bean.getClass();
    final Class<?>[] classes = clazz.getClasses();

    addDeclaredFields(clazz, fields);/*from  w ww  . ja  v a  2  s.c  o  m*/

    for (int i = 0; i < classes.length; i++) {
        addDeclaredFields(classes[i], fields);
    }

    try {
        for (final Field field : fields) {
            final boolean originalValue = field.isAccessible();
            field.setAccessible(true);
            final Annotation annotation = field.getAnnotation(getSupportedAnnotation());

            if (annotation != null) {
                processField(field, annotation, bean, beanName);
            }

            field.setAccessible(originalValue);
        }
    } catch (final IllegalAccessException e) {
        log.warn("Could not access field: " + e.getMessage(), e);
    }

    return bean;
}

From source file:py.una.pol.karaku.dao.entity.interceptors.TimeInterceptor.java

@Override
public void intercept(Operation op, Field f, Object bean) {

    Object o = ReflectionUtils.getField(f, bean);

    if (o == null) {
        return;/*from w w w.j  a  v  a  2s . c  o  m*/
    }

    Time t = f.getAnnotation(Time.class);
    Date date = (Date) o;
    Calendar c = Calendar.getInstance();
    c.setTime(date);

    if ((t == null) || t.type().equals(Time.Type.DATE)) {
        this.handleDate(c);
    } else if (t.type().equals(Time.Type.TIME)) {
        this.handleTime(c);
    }
    // DATETIME no es manejado por que no requeire ningun
    // trato especial

    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    ReflectionUtils.setField(f, bean, c.getTime());
}

From source file:com.cognifide.slice.mapper.GenericSlingMapper.java

/**
 * Gets name of property associated with given field. Usually - same as field name, but can be overridden
 * using {@link JcrProperty} annotation.
 * //from  w  ww. j  av  a 2  s.c om
 * @param field field to get associated property name for
 * @return property name associated with given field, never null.
 */
private String getPropertyName(Field field) {
    final JcrProperty annotation = field.getAnnotation(JcrProperty.class);
    if ((annotation != null) && StringUtils.isNotBlank(annotation.value())) {
        return annotation.value();
    }
    return field.getName();
}

From source file:in.hatimi.nosh.support.CmdLineManager.java

private boolean injectField(CommandLine cmdLine, Object target, Field field) {
    CmdLineOption clo = field.getAnnotation(CmdLineOption.class);
    if (clo == null) {
        return true;
    }/*w ww. java 2s.  c  o m*/

    String nameToUse = clo.name();
    if (StringUtils.isBlank(nameToUse)) {
        nameToUse = clo.longName();
    }

    if (clo.argCount() == 0) {
        if (cmdLine.hasOption(nameToUse)) {
            return injectBoolean(target, field, true);
        } else {
            return injectBoolean(target, field, false);
        }
    }
    if (clo.argCount() == 1) {
        String value = cmdLine.getOptionValue(nameToUse);
        if (value != null) {
            return injectString(target, field, value);
        }
    } else if (clo.valueSeparator() > 0) {
        Properties props = cmdLine.getOptionProperties(nameToUse);
        if (props != null) {
            return injectProperties(target, field, props);
        }
    } else if (clo.argCount() > 1) {
        String[] values = cmdLine.getOptionValues(nameToUse);
        if (values != null && values.length > 0) {
            return injectStringArray(target, field, values);
        }
    }
    return true;
}