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:be.fedict.eid.applet.service.impl.tlv.TlvParser.java

private static <T> T parseThrowing(byte[] file, Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    Field[] fields = tlvClass.getDeclaredFields();
    Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    for (Field field : fields) {
        TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null == tlvFieldAnnotation) {
            continue;
        }/*  w  w  w . j a v a2s  . c o m*/
        int tagId = tlvFieldAnnotation.value();
        if (tlvFields.containsKey(new Integer(tagId))) {
            throw new IllegalArgumentException("TLV field duplicate: " + tagId);
        }
        tlvFields.put(new Integer(tagId), field);
    }
    T tlvObject = tlvClass.newInstance();

    int idx = 0;
    while (idx < file.length - 1) {
        byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            Field tlvField = tlvFields.get(new Integer(tag));
            Class<?> tlvType = tlvField.getType();
            ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            LOG.debug("setting field: " + tlvField.getName());
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

From source file:com.microsoft.rest.Validator.java

/**
 * Validates a user provided required parameter to be not null.
 * A {@link ServiceException} is thrown if a property fails the validation.
 *
 * @param parameter the parameter to validate
 * @throws ServiceException failures wrapped in {@link ServiceException}
 *///  w ww .j  ava2s . c  o m
public static void validate(Object parameter) throws ServiceException {
    // Validation of top level payload is done outside
    if (parameter == null) {
        return;
    }

    Class parameterType = parameter.getClass();
    if (ClassUtils.isPrimitiveOrWrapper(parameterType) || parameterType.isEnum()
            || ClassUtils.isAssignable(parameterType, LocalDate.class)
            || ClassUtils.isAssignable(parameterType, DateTime.class)
            || ClassUtils.isAssignable(parameterType, String.class)
            || ClassUtils.isAssignable(parameterType, DateTimeRfc1123.class)
            || ClassUtils.isAssignable(parameterType, Period.class)) {
        return;
    }

    Field[] fields = FieldUtils.getAllFields(parameterType);
    for (Field field : fields) {
        field.setAccessible(true);
        JsonProperty annotation = field.getAnnotation(JsonProperty.class);
        Object property;
        try {
            property = field.get(parameter);
        } catch (IllegalAccessException e) {
            throw new ServiceException(e);
        }
        if (property == null) {
            if (annotation != null && annotation.required()) {
                throw new ServiceException(
                        new IllegalArgumentException(field.getName() + " is required and cannot be null."));
            }
        } else {
            try {
                Class propertyType = property.getClass();
                if (ClassUtils.isAssignable(propertyType, List.class)) {
                    List<?> items = (List<?>) property;
                    for (Object item : items) {
                        Validator.validate(item);
                    }
                } else if (ClassUtils.isAssignable(propertyType, Map.class)) {
                    Map<?, ?> entries = (Map<?, ?>) property;
                    for (Map.Entry<?, ?> entry : entries.entrySet()) {
                        Validator.validate(entry.getKey());
                        Validator.validate(entry.getValue());
                    }
                } else if (parameter.getClass().getDeclaringClass() != propertyType) {
                    Validator.validate(property);
                }
            } catch (ServiceException ex) {
                IllegalArgumentException cause = (IllegalArgumentException) (ex.getCause());
                if (cause != null) {
                    // Build property chain
                    throw new ServiceException(
                            new IllegalArgumentException(field.getName() + "." + cause.getMessage()));
                } else {
                    throw ex;
                }
            }
        }
    }
}

From source file:com.scvngr.levelup.core.test.JsonTestUtil.java

/**
 * Reflects a {@link JsonType} from a field's {@link JsonValueType} annotation.
 *
 * @param field Field with a JsonValueType annotation to read from.
 * @return the {@link JsonType} of the field.
 *///  www .  j av a  2s.  co m
@NonNull
private static JsonType reflectJsonType(@NonNull final Field field) {
    final JsonValueType annotation = field.getAnnotation(JsonValueType.class);
    return annotation.value();
}

From source file:de.micromata.genome.util.bean.PropertyDescriptorUtils.java

/**
 * Find anotation first on getter than from field.
 *
 * @param <T> the generic type//  w  w w .  j  a  va2  s  .c o m
 * @param beanClazz the bean clazz
 * @param pd the pd
 * @param anotclass the anotclass
 * @return the t
 */
public static <T extends Annotation> T findAnotation(Class<?> beanClazz, PropertyDescriptor pd,
        Class<T> anotclass) {
    Method rm = pd.getReadMethod();
    if (rm != null) {
        T anot = rm.getAnnotation(anotclass);
        if (anot != null) {
            return anot;
        }
    }
    Field field = PrivateBeanUtils.findField(beanClazz, pd.getName());
    if (field == null) {
        return null;
    }
    T anot = field.getAnnotation(anotclass);
    return anot;
}

From source file:com.greenline.hrs.admin.cache.redis.util.RedisInfoParser.java

/**
 * RedisInfoMapT?RedisInfoMapRedis?/*  w  w  w  . j  a v a  2s.co m*/
 * RedisServerInfoPO
 *
 * @param instanceType class
 * @param redisInfoMap Map
 * @param <T>          
 * @return instanceTypeinfomapnullinfoMap?instancenullRedisServerInfoPO
 */
public static <T> T parserRedisInfo(Class<T> instanceType, Map<String, String> redisInfoMap) {
    if (instanceType == null || redisInfoMap == null || redisInfoMap.isEmpty()) {
        return null;
    }
    T instance = null;
    try {
        instance = instanceType.newInstance();
    } catch (Exception e) {
        LOG.error("Instance:" + instanceType.getName(), e);
        return null;
    }
    Field[] fields = instanceType.getDeclaredFields();
    String inputName = null;
    for (Field field : fields) {
        ParserField parserField = field.getAnnotation(ParserField.class);
        if (parserField != null) {
            inputName = parserField.inputName();
        } else {
            inputName = field.getName();
        }
        if (redisInfoMap.containsKey(inputName)) {
            field.setAccessible(true);
            try {
                field.set(instance, ConvertUtils.convert(redisInfoMap.get(inputName), field.getType()));
            } catch (Exception e) {
                LOG.error("Field:" + field.getName() + "\t|\t value:" + redisInfoMap.get(inputName), e);
            }
        }
    }
    return instance;
}

From source file:be.fedict.commons.eid.consumer.tlv.TlvParser.java

private static <T> T parseThrowing(final byte[] file, final Class<T> tlvClass) throws InstantiationException,
        IllegalAccessException, DataConvertorException, UnsupportedEncodingException {
    final Field[] fields = tlvClass.getDeclaredFields();
    final Map<Integer, Field> tlvFields = new HashMap<Integer, Field>();
    final T tlvObject = tlvClass.newInstance();
    for (Field field : fields) {
        final TlvField tlvFieldAnnotation = field.getAnnotation(TlvField.class);
        if (null != tlvFieldAnnotation) {
            final int tagId = tlvFieldAnnotation.value();
            if (tlvFields.containsKey(new Integer(tagId))) {
                throw new IllegalArgumentException("TLV field duplicate: " + tagId);
            }//from  w  w  w .  j  ava2  s  .  c o m
            tlvFields.put(new Integer(tagId), field);
        }
        final OriginalData originalDataAnnotation = field.getAnnotation(OriginalData.class);
        if (null != originalDataAnnotation) {
            field.setAccessible(true);
            field.set(tlvObject, file);
        }
    }

    int idx = 0;
    while (idx < file.length - 1) {
        final byte tag = file[idx];
        idx++;
        byte lengthByte = file[idx];
        int length = lengthByte & 0x7f;
        while ((lengthByte & 0x80) == 0x80) {
            idx++;
            lengthByte = file[idx];
            length = (length << 7) + (lengthByte & 0x7f);
        }
        idx++;
        if (0 == tag) {
            idx += length;
            continue;
        }
        if (tlvFields.containsKey(new Integer(tag))) {
            final Field tlvField = tlvFields.get(new Integer(tag));
            final Class<?> tlvType = tlvField.getType();
            final ConvertData convertDataAnnotation = tlvField.getAnnotation(ConvertData.class);
            final byte[] tlvValue = copy(file, idx, length);
            Object fieldValue;
            if (null != convertDataAnnotation) {
                final Class<? extends DataConvertor<?>> dataConvertorClass = convertDataAnnotation.value();
                final DataConvertor<?> dataConvertor = dataConvertorClass.newInstance();
                fieldValue = dataConvertor.convert(tlvValue);
            } else if (String.class == tlvType) {
                fieldValue = new String(tlvValue, "UTF-8");
            } else if (Boolean.TYPE == tlvType) {
                fieldValue = true;
            } else if (tlvType.isArray() && Byte.TYPE == tlvType.getComponentType()) {
                fieldValue = tlvValue;
            } else {
                throw new IllegalArgumentException("unsupported field type: " + tlvType.getName());
            }
            if (null != tlvField.get(tlvObject) && false == tlvField.getType().isPrimitive()) {
                throw new RuntimeException("field was already set: " + tlvField.getName());
            }
            tlvField.setAccessible(true);
            tlvField.set(tlvObject, fieldValue);
        } else {
            LOG.debug("unknown tag: " + (tag & 0xff) + ", length: " + length);
        }
        idx += length;
    }
    return tlvObject;
}

From source file:com.opensymphony.xwork2.util.AnnotationUtils.java

/**
 * Adds all fields with the specified Annotation of class clazz and its superclasses to allFields
 *
 * @param annotationClass the {@link Annotation}s to find
 * @param clazz The {@link Class} to inspect
 * @param allFields list of all fields/*from w w w. j  av  a 2s .  c o m*/
 */
public static void addAllFields(Class<? extends Annotation> annotationClass, Class clazz,
        List<Field> allFields) {

    if (clazz == null) {
        return;
    }

    Field[] fields = clazz.getDeclaredFields();

    for (Field field : fields) {
        Annotation ann = field.getAnnotation(annotationClass);
        if (ann != null) {
            allFields.add(field);
        }
    }
    addAllFields(annotationClass, clazz.getSuperclass(), allFields);
}

From source file:fr.paris.lutece.plugins.contextinclude.service.parameter.ContextParameterService.java

/**
 * Depopulate.//from   ww  w.j av  a  2 s  .c  o m
 *
 * @param contextParameter the context parameter
 * @return the map
 */
private static Map<String, Object> depopulate(IContextParameter contextParameter) {
    Map<String, Object> mapAttributes = new HashMap<String, Object>();

    for (java.lang.reflect.Field field : ContextParameter.class.getDeclaredFields()) {
        ContextAttribute attribute = field.getAnnotation(ContextAttribute.class);

        if (attribute != null) {
            String strAttributeKey = attribute.value();

            try {
                field.setAccessible(true);

                Object attributeValue = ReflectionUtils.getField(field, contextParameter);
                mapAttributes.put(strAttributeKey, attributeValue);
            } catch (SecurityException e) {
                AppLogService.error(e);
            }
        }
    }

    return mapAttributes;
}

From source file:org.chorusbdd.chorus.spring.SpringContextInjector.java

private static void injectResourceFields(ApplicationContext springContext, Object handler, Class handlerClass) {
    ChorusLog log = ChorusLogFactory.getLog(SpringContextInjector.class);

    //inject handler fields with the Spring beans
    Field[] fields = handlerClass.getDeclaredFields();
    for (Field field : fields) {
        Resource resourceAnnotation = field.getAnnotation(Resource.class);
        if (resourceAnnotation != null) {
            boolean beanNameInAnnotation = !"".equals(resourceAnnotation.name());
            String name = beanNameInAnnotation ? resourceAnnotation.name() : field.getName();
            Object bean = springContext.getBean(name);
            log.trace("Found spring Resource annotation for field " + field
                    + " will attempt to inject Spring bean " + bean);
            if (bean == null) {
                log.error(/*from   ww w. j  av a2  s  . c o m*/
                        "Failed to set @Resource (" + name + "). No such bean exists in application context.");
            }
            try {
                field.setAccessible(true);
                field.set(handler, bean);
            } catch (IllegalAccessException e) {
                log.error("Failed to set @Resource (" + name + ") with bean of type: " + bean.getClass(), e);
            }
        }
    }

    Class superclass = handlerClass.getSuperclass();
    if (superclass != Object.class) {
        injectResourceFields(springContext, handler, superclass);
    }
}

From source file:com.linkedin.pinot.tools.segment.converter.ColumnarToStarTreeConverter.java

/**
 * Helper method to print usage at the command line interface.
 *//*  www. jav  a2 s .c o m*/
private static void printUsage() {
    System.out.println("Usage: ColumnarToStarTreeConverter");
    for (Field field : ColumnarToStarTreeConverter.class.getDeclaredFields()) {

        if (field.isAnnotationPresent(Option.class)) {
            Option option = field.getAnnotation(Option.class);

            System.out.println(String.format("\t%-15s: %s (required=%s)", option.name(), option.usage(),
                    option.required()));
        }
    }
}