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:it.sample.parser.util.CommonsUtil.java

/**
 * Metodo di utilita' che copia i campi non nulli della classe sorgente in quelli della classe di destinazione
 * //from w  w w . j  a v a2 s  . c  om
 * @param source
 * @param destination
 */
public static <K, T> void copyNotNullProperties(K source, T destination) {
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(source);
    if (descriptors != null) {
        for (PropertyDescriptor descriptor : descriptors) {
            try {
                String propertyName = descriptor.getName();
                Field field = getDeclaredField(propertyName, source.getClass());

                if (field != null && field.getAnnotation(IgnoreField.class) == null) {
                    boolean wasAccessible = field.isAccessible();
                    field.setAccessible(true);

                    if (PropertyUtils.getReadMethod(descriptor) != null) {
                        Object val = PropertyUtils.getSimpleProperty(source, propertyName);
                        if (val != null && descriptor.getWriteMethod() != null) {
                            PropertyUtils.setProperty(destination, propertyName, val);
                        }
                    }
                    field.setAccessible(wasAccessible);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:nz.co.senanque.validationengine.ValidationUtils.java

public static void setDefaults(ValidationObject object) {
    for (Field field : object.getClass().getDeclaredFields()) {
        XmlElement xmlElement = field.getAnnotation(XmlElement.class);
        if (xmlElement != null && hasText(xmlElement.defaultValue())) {
            String value = xmlElement.defaultValue();
            Method setter = figureSetter(field.getName(), object.getClass());
            Class<?> type = setter.getParameterTypes()[0];
            try {
                setter.invoke(object, ConvertUtils.convertToObject(type, value, null));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }/*from   w  ww  . j a va  2s. c  om*/
        }
        String n = field.getName();
        if (n.startsWith("m_")) {
            n = n.substring(2);
        }
        try {
            Method getter = figureGetter(n, object.getClass());
            Annotation unknown = getter.getAnnotation(Unknown.class);
            if (unknown != null) {
                object.getMetadata().addUnknown(field.getName());
            }
        } catch (RuntimeException e) {
            // ignore
        }
    }
}

From source file:com.ykun.commons.utils.excel.ExcelUtils.java

/**
 * xlsheaders/*from w  w w.  j  a va 2s  . c o m*/
 *
 * @param list    the list
 * @param headers the headers
 * @param out     the out
 */
public static <T> void export(List<T> list, List<String> headers, OutputStream out) {
    // ?
    if (list == null || list.size() == 0) {
        return;
    }

    try {
        Workbook workbook = new XSSFWorkbook(); // XSSFWorkbook
        Sheet sheet = workbook.createSheet(); // ?Sheet

        // ?
        int rowNo = 0;
        CellStyle headerStyle = createHeaderStyle(workbook);
        if (headers != null && headers.size() > 0) {
            Row row = sheet.createRow(rowNo++);
            for (int i = 0; i < headers.size(); i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(headerStyle);
                cell.setCellValue(headers.get(i));
            }
        }

        // ?
        CellStyle normalStyle = createNormalStyle(workbook);
        for (T t : list) {
            Row row = sheet.createRow(rowNo++);
            Field[] fields = t.getClass().getDeclaredFields();
            int column = 0;
            for (int i = 0; i < fields.length; i++) {
                Object value;
                Field field = fields[i];
                ExcelField excelField = field.getAnnotation(ExcelField.class);
                if (excelField != null && !excelField.ignore()) {
                    String methodName = PREFIX_GETTER + StringUtils.capitalize(field.getName()); // get???getisEnable?
                    Method method = t.getClass().getMethod(methodName, new Class[] {});
                    value = method.invoke(t, new Object[] {});
                } else if (excelField != null && excelField.ignore()) {
                    continue;
                } else {
                    String methodName = PREFIX_GETTER + StringUtils.capitalize(field.getName()); // get???getisEnable?
                    Method method = t.getClass().getMethod(methodName, new Class[] {});
                    value = method.invoke(t, new Object[] {});
                }
                row.setRowStyle(normalStyle);
                addCell(row, column++, value, excelField);
            }
        }
        workbook.write(out);
    } catch (Exception e) {
        logger.error("Export error:", e);
        throw new RuntimeException(e);
    }
}

From source file:com.alfresco.orm.ORMUtil.java

public static void executeAssociation(final AlfrescoContent alfrescoContent, final BeanFactory beanFactory,
        final ServiceRegistry serviceRegistry)
        throws ORMException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    NodeRef nodeRef = getNodeRef(alfrescoContent);
    List<Field> fields = new ArrayList<Field>();
    ReflectionUtil.getFields(alfrescoContent.getClass(), fields);
    for (Field field : fields) {
        if (field.isAnnotationPresent(AlfrescoAssociation.class)) {
            AlfrescoQName alfrescoQName = field.getAnnotation(AlfrescoQName.class);
            if (null == alfrescoQName) {
                throw new ORMException("please add alfresco quname aspect to the association field: " + field);
            }/*  w  w w  .jav  a 2 s.  c  o  m*/
            List<AlfrescoContent> associationAlfrescoORMs = getAsscoiationObject(alfrescoContent, field);
            QName qName = QName.createQName(alfrescoQName.namespaceURI(), alfrescoQName.localName());
            removeAllAssociation(serviceRegistry, nodeRef, qName);
            for (AlfrescoContent associationAlfrescoORM : associationAlfrescoORMs) {
                if (StringUtils.isNotBlank(associationAlfrescoORM.getNodeUUID())) {
                    // TODO: understand requirement and check that do we need to update pojo or just need to update association
                    //UpdateHelper.getUpdateHelper().update(associationAlfrescoORM);
                    NodeRef associationNodeRef = getNodeRef(associationAlfrescoORM);
                    List<AssociationRef> associationRefs = serviceRegistry.getNodeService()
                            .getTargetAssocs(nodeRef, qName);

                    if (!associationRefs.isEmpty()) {
                        boolean doAdd = true;
                        for (AssociationRef associationRef : associationRefs) {
                            if (associationRef.getTargetRef().equals(associationNodeRef)) {
                                doAdd = false;
                            }
                        }
                        if (doAdd) {
                            serviceRegistry.getNodeService().createAssociation(nodeRef, associationNodeRef,
                                    qName);
                        }
                    } else {
                        serviceRegistry.getNodeService().createAssociation(nodeRef, associationNodeRef, qName);
                    }

                } else {
                    CreateHelper.getCreateHelper().save(associationAlfrescoORM);
                    NodeRef associationNodeRef = getNodeRef(associationAlfrescoORM);
                    serviceRegistry.getNodeService().createAssociation(nodeRef, associationNodeRef, qName);
                }
            }

        }
    }
}

From source file:net.sourceforge.stripes.integration.spring.SpringHelper.java

/**
 * Looks for all methods and fields annotated with {@code @SpringBean} and attempts
 * to lookup and inject a managed bean into the field/property. If any annotated
 * element cannot be injected an exception is thrown.
 *
 * @param bean the bean into which to inject spring beans
 * @param ctx the Spring application context
 *//*from   w  ww.j a  v a  2  s  . c  om*/
public static void injectBeans(Object bean, ApplicationContext ctx) {
    // First inject any values using annotated methods
    for (Method m : getMethods(bean.getClass())) {
        try {
            SpringBean springBean = m.getAnnotation(SpringBean.class);
            boolean nameSupplied = !"".equals(springBean.value());
            String name = nameSupplied ? springBean.value() : methodToPropertyName(m);
            Class<?> beanType = m.getParameterTypes()[0];
            Object managedBean = findSpringBean(ctx, name, beanType, !nameSupplied);
            m.invoke(bean, managedBean);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Exception while trying to lookup and inject " + "a Spring bean into a bean of type "
                            + bean.getClass().getSimpleName() + " using method " + m.toString(),
                    e);
        }
    }

    // And then inject any properties that are annotated
    for (Field f : getFields(bean.getClass())) {
        try {
            SpringBean springBean = f.getAnnotation(SpringBean.class);
            boolean nameSupplied = !"".equals(springBean.value());
            String name = nameSupplied ? springBean.value() : f.getName();
            Object managedBean = findSpringBean(ctx, name, f.getType(), !nameSupplied);
            f.set(bean, managedBean);
        } catch (Exception e) {
            throw new StripesRuntimeException(
                    "Exception while trying to lookup and inject " + "a Spring bean into a bean of type "
                            + bean.getClass().getSimpleName() + " using field access on field " + f.toString(),
                    e);
        }
    }
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

private static void processIntegrationService(Object targetObject, Class<? extends Object> clazz)
        throws AutomationFrameworkException {
    if (clazz == null)
        return;/*from w  ww .j a  va 2  s . co  m*/
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.getAnnotation(CCProperty.class) != null) {
            processPropertyField(targetObject, field);
        }
    }
    processIntegrationService(targetObject, clazz.getSuperclass());
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

private static <T extends Object> void processCCFeatureForObject(T entity, Class<? extends Object> clazz)
        throws AutomationFrameworkException {
    if (clazz == null)
        return;/*from w  w  w. j  a v a  2 s  .c om*/
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.getAnnotation(CCFeature.class) != null) {
            processCCFeatureField(entity, field);
        } else if (field.getAnnotation(CCIntegrationService.class) != null) {
            createIntegrationService(field, entity);
        } else if (field.getAnnotation(CCProperty.class) != null) {
            processPropertyField(entity, field);
        }
    }
    processCCFeatureForObject(entity, (Class<? extends Object>) clazz.getSuperclass());
}

From source file:net.minecraftforge.common.config.ConfigManager.java

private static String getName(Field f) {
    if (f.isAnnotationPresent(Name.class))
        return f.getAnnotation(Name.class).value();
    return f.getName();
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

/**
 * @param targetObject/*  w  w  w. ja  va  2s  . c om*/
 * @param fields
 * @param i
 * @throws AutomationFrameworkException
 */
public static void processPropertyField(Object targetObject, Field field) throws AutomationFrameworkException {
    try {
        CCProperty properties = field.getAnnotation(CCProperty.class);
        StringBuffer value = new StringBuffer("");
        for (String prop : properties.value()) {
            value.append(AutomationMain.getProperty(prop));
        }
        field.set(targetObject, value.toString());
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: "
                        + targetObject.getClass().getSimpleName() + " Thread ID:"
                        + Thread.currentThread().getId(),
                e);
    }
}

From source file:com.github.jasonruckman.sidney.core.JavaTypeRefBuilder.java

public static TypeRef buildTypeRef(Type type, TypeBindings parentBindings, Field field) {
    JavaType jt;//from   www.  ja  v  a  2  s.c o m
    TypeBindings typeBindings;

    typeBindings = Types.binding(type, parentBindings);
    jt = Types.type(type, parentBindings);
    TypeRef ref;
    if (field == null) {
        ref = new TypeRef(jt.getRawClass());
    } else {
        Hint hint = field.getAnnotation(Hint.class);
        if (hint != null) {
            ref = new TypeRef.TypeFieldRef(hint.value(), field);
        } else {
            ref = new TypeRef.TypeFieldRef(jt.getRawClass(), field);
        }
    }

    for (Field subField : Fields.getAllFields(jt.getRawClass())) {
        Type subType = subField.getGenericType();
        TypeRef subRef = buildTypeRef(subType, typeBindings, subField);
        ref.addField((TypeRef.TypeFieldRef) subRef);
    }

    if (ParameterizedType.class.isAssignableFrom(type.getClass())) {
        ParameterizedType t = (ParameterizedType) type;
        for (Type actualTypeArg : t.getActualTypeArguments()) {
            ref.addTypeParameter(buildTypeRef(actualTypeArg, parentBindings, null));
        }
    } else if (TypeVariable.class.isAssignableFrom(type.getClass())) {
        TypeVariable t = (TypeVariable) type;
        for (Type typeBound : t.getBounds()) {
            ref.addTypeParameter(buildTypeRef(typeBound, parentBindings, null));
        }
    } else if (GenericArrayType.class.isAssignableFrom(type.getClass())) {
        GenericArrayType t = (GenericArrayType) type;
        ref.addTypeParameter(buildTypeRef(t.getGenericComponentType(), parentBindings, null));
    }

    if (jt.isArrayType() && !GenericArrayType.class.isAssignableFrom(type.getClass())) {
        ArrayType arrType = (ArrayType) jt;
        ref.addTypeParameter(buildTypeRef(arrType.getContentType().getRawClass(), null, null));
    }

    return ref;
}