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.khubla.cbean.serializer.impl.json.JSONListFieldSerializer.java

@Override
public void delete(Object o, Field field) throws SerializerException {
    final Property property = field.getAnnotation(Property.class);
    if ((null != property) && (property.cascadeDelete() == true)) {
        try {//from   w  w w  .ja  va2s . c  o m
            /*
             * get the parameterized type
             */
            final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            final Class<?> containedType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
            /*
             * get cBean
             */
            final CBean<Object> cBean = CBeanServer.getInstance().getCBean(containedType);
            /*
             * get the array object
             */
            @SuppressWarnings("unchecked")
            final List<Object> list = (List<Object>) PropertyUtils.getProperty(o, field.getName());
            /*
             * iterate
             */
            for (final Object obj : list) {
                final String key = cBean.getId(obj);
                cBean.delete(new CBeanKey(key));
            }
        } catch (final Exception e) {
            throw new SerializerException(e);
        }
    }
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * To upperCase object String field/* w  w  w.j  a  v  a 2 s .  co m*/
 * 
 * @param all
 *            default is false. true means toUpperCase all String field, false toUpperCase the fields have
 *            net.kamhon.ieagle.vo.core.annotation.ToUpperCase.
 * 
 * @param objects
 */
public static void toUpperCaseProperties(boolean all, Object... objects) {
    for (Object object : objects) {
        if (object == null) {
            continue;
        }

        // getter for String field only
        Map<String, Method> getterMap = new HashMap<String, Method>();
        // setter for String field only
        Map<String, Method> setterMap = new HashMap<String, Method>();

        Class<?> clazz = object.getClass();

        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            /*
             * log.debug("method = " + method.getName());
             * log.debug("method.getParameterTypes().length = " +
             * method.getParameterTypes().length); if
             * (method.getParameterTypes().length == 1)
             * log.debug("method.getParameterTypes()[0] = " +
             * method.getParameterTypes()[0]);
             * log.debug("method.getReturnType() = " +
             * method.getReturnType());
             * log.debug("================================================="
             * );
             */
            if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                    && method.getReturnType().equals(String.class)) {

                // if method name is getXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                getterMap.put(fieldName, method);
            } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0] == String.class
                    && method.getReturnType().equals(void.class)) {
                // log.debug("setter = " + method.getName());

                // if method name is setXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                setterMap.put(fieldName, method);
            }
        }

        // if the key exists in both getter & setter
        for (String key : getterMap.keySet()) {
            if (setterMap.containsKey(key)) {
                try {
                    Method getterMethod = getterMap.get(key);
                    Method setterMethod = setterMap.get(key);

                    // if not all, check on Field
                    if (!all) {
                        Field field = null;

                        Class<?> tmpClazz = clazz;
                        // looping up to superclass to get decleared field
                        do {
                            try {
                                field = tmpClazz.getDeclaredField(key);
                            } catch (Exception ex) {
                                // do nothing
                            }

                            if (field != null) {
                                break;
                            }

                            tmpClazz = tmpClazz.getSuperclass();
                        } while (tmpClazz != null);

                        ToUpperCase toUpperCase = field.getAnnotation(ToUpperCase.class);
                        if (toUpperCase == null || toUpperCase.upperCase() == false) {
                            continue;
                        }
                    }

                    String value = (String) getterMethod.invoke(object, new Object[] {});

                    if (StringUtils.isNotBlank(value))
                        setterMethod.invoke(object, value.toUpperCase());

                } catch (Exception ex) {
                    // log.error("Getter Setter for " + key + " has error ", ex);
                }
            }
        }
    }
}

From source file:com.trigonic.utils.spring.cmdline.CommandLineMetaData.java

private void populateOperandFields(Class<?> beanClass) {
    Class<?> superClass = beanClass.getSuperclass();
    if (!superClass.equals(Object.class)) {
        populateOperandFields(superClass);
    }/* w w w  .  j a  v  a 2 s .c o  m*/
    for (Field field : beanClass.getDeclaredFields()) {
        Operand operand = field.getAnnotation(Operand.class);
        if (operand != null) {
            checkWriteableProperty(operand, beanClass, field);
            operands.put(operand, new OperandFieldHandler(operand, field));
        }
    }
}

From source file:com.feilong.framework.netpay.payment.BasePaymentTest.java

/**
 *  file path./*from w ww  .ja  va 2 s. c  om*/
 *
 * @return the file path
 */
private String getFilePath() {
    Field declaredField = FieldUtil.getDeclaredField(this.getClass(), "paymentAdaptor");
    Qualifier qualifier = declaredField.getAnnotation(Qualifier.class);
    String paymentAdaptorName = qualifier.value();
    String fileName = paymentAdaptorName + DateUtil.date2String(new Date(), DatePattern.TIMESTAMP);

    String folderPath = SystemUtils.USER_HOME + "\\feilong\\payment\\" + paymentAdaptorName;
    String filePath = folderPath + "\\" + fileName + ".html";
    return filePath;
}

From source file:com.impetus.kundera.metadata.processor.AbstractEntityFieldProcessor.java

/**
 * Gets the valid jpa column./*ww w.  jav a2  s .c  o m*/
 * 
 * @param entity
 *            the entity
 * @param f
 *            the f
 * 
 * @return the valid jpa column
 */
protected final String getValidJPAColumnName(Class<?> entity, Field f) {

    String name = null;

    if (f.isAnnotationPresent(Column.class)) {
        Column c = f.getAnnotation(Column.class);
        if (!c.name().isEmpty()) {
            name = c.name();
        } else {
            name = f.getName();
        }
    } else if (f.isAnnotationPresent(Basic.class)) {
        name = f.getName();
    }

    if (f.isAnnotationPresent(Temporal.class)) {
        if (!f.getType().equals(Date.class)) {
            log.error("@Temporal must map to java.util.Date for @Entity(" + entity.getName() + "." + f.getName()
                    + ")");
            return name;
        }
        if (null == name) {
            name = f.getName();
        }
    }
    return name;
}

From source file:com.aestheticsw.jobkeywords.shared.config.LogInjector.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String name) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            // make the field accessible if defined private
            ReflectionUtils.makeAccessible(field);
            if (field.getAnnotation(Log.class) != null) {
                Logger log = LoggerFactory.getLogger(bean.getClass());
                field.set(bean, log);/*  www  .ja va2s.c  om*/
            }
        }
    });
    return bean;
}

From source file:org.grails.datastore.mapping.model.config.DefaultMappingConfigurationStrategy.java

public PersistentProperty getIdentity(Class javaClass, MappingContext context) {
    final ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(javaClass);

    for (Field field : cpf.getJavaClass().getDeclaredFields()) {
        final Id annotation = field.getAnnotation(Id.class);
        if (annotation != null) {
            PersistentEntity entity = context.getPersistentEntity(javaClass.getName());
            PropertyDescriptor pd = cpf.getPropertyDescriptor(field.getName());
            return propertyFactory.createIdentity(entity, context, pd);
        }/*from ww w  .j  a  v  a2 s. com*/
    }
    throw new IllegalMappingException("No identifier specified for persistent class: " + javaClass.getName());
}

From source file:com.billing.ng.plugin.Parameters.java

/**
 * Returns the field name of javabeans properties annotated with the
 * {@link Parameter} annotation./*from w  ww .j  a  v  a  2  s . co m*/
 *
 * @param type plugin class with parameter annotations
 * @return map of collected parameter field names and the associated annotation
 */
public Map<String, Parameter> getAnnotatedFields(Class<T> type) {
    Map<String, Parameter> fields = new HashMap<String, Parameter>();

    // collect public member methods of the class, including those defined on the interface
    // or those inherited from a super class or super interface.
    for (Method method : type.getMethods()) {
        Parameter annotation = method.getAnnotation(Parameter.class);
        if (annotation != null) {
            if (method.getName().startsWith("get") || method.getName().startsWith("set")) {
                fields.put(ClassUtils.getFieldName(method.getName()), annotation);
            }
        }
    }

    // collection all field annotations, including private fields that
    // we can to access via a public accessor method
    Class klass = type;
    while (klass != null) {
        for (Field field : klass.getDeclaredFields()) {
            Parameter annotation = field.getAnnotation(Parameter.class);
            if (annotation != null) {
                fields.put(field.getName(), annotation);
            }
        }

        // try the super class
        klass = klass.getSuperclass();
    }

    return fields;
}

From source file:com.graphaware.importer.cache.BaseCaches.java

/**
 * {@inheritDoc}/*from   w  w  w.j av  a 2  s . c o m*/
 */
@Override
public Set<String> neededCaches(Importer importer) {
    Assert.notNull(importer);

    Set<String> result = new HashSet<>();

    for (Field field : ReflectionUtils.getAllFields(importer.getClass())) {
        if (field.getAnnotation(InjectCache.class) != null) {
            result.add(field.getAnnotation(InjectCache.class).name());
        }
    }

    return result;
}

From source file:org.grails.datastore.mapping.keyvalue.mapping.config.AnnotationKeyValueMappingFactory.java

@Override
public KeyValue createMappedForm(PersistentProperty mpp) {
    final Class javaClass = mpp.getOwner().getJavaClass();
    final ClassPropertyFetcher cpf = ClassPropertyFetcher.forClass(javaClass);

    final PropertyDescriptor pd = cpf.getPropertyDescriptor(mpp.getName());
    final KeyValue kv = super.createMappedForm(mpp);
    Index index = AnnotationUtils.getAnnotation(pd.getReadMethod(), Index.class);

    if (index == null) {
        final Field field = ReflectionUtils.findField(javaClass, mpp.getName());
        if (field != null) {
            ReflectionUtils.makeAccessible(field);
            index = field.getAnnotation(Index.class);
        }/*from  w  w w .ja  v  a2 s.c  om*/
    }
    if (index != null) {
        kv.setIndex(true);
    }

    return kv;
}