Example usage for java.lang.reflect Field isAnnotationPresent

List of usage examples for java.lang.reflect Field isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Field isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.sun.inject.Injector.java

public static final void injectFragment(Fragment frgment, View view) {
    if (frgment == null || view == null)
        return;/*from   w  w  w.j  a  va 2 s.  c om*/
    Field[] fields = frgment.getClass().getDeclaredFields();
    if (fields == null || fields.length == 0)
        return;
    try {
        for (Field field : fields) {
            if (field.isAnnotationPresent(InjectView.class)) {
                injectViewByFragment(field, frgment, view);
            } else if (field.isAnnotationPresent(InjectFragment.class)) {
                injectFragmentByFragment(field, frgment);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sun.inject.Injector.java

/**
 * Injects all fields that are marked with the {@link InjectView} annotation.
 * <p>//from  w  ww .  j  a va2  s. co  m
 * For each field marked with the InjectView annotation, a call to {@link Activity#findViewById(int)} will be made, passing in the resource id stored in the
 * value() method of the InjectView annotation as the int parameter, and the result of this call will be assigned to the field.
 * 
 * @throws IllegalStateException
 *             if injection fails, common causes being that you have used an invalid id value, or you haven't called setContentView() on your Activity.
 */
public static final void injectActivity(Activity activity) {
    if (activity == null)
        return;
    Field[] fields = activity.getClass().getDeclaredFields();
    if (fields == null || fields.length == 0)
        return;
    try {
        for (Field field : fields) {
            if (field.isAnnotationPresent(InjectView.class)) {
                injectViewByActivity(field, activity);
            } else if (field.isAnnotationPresent(InjectFragment.class)) {
                injectFragmentByActivity(field, activity);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.github.benas.jpopulator.impl.BeanValidationRandomizer.java

/**
 * Generate a random value according to the validation constraint present on a field.
 *
 * @param field the field to populate/*  www . j a  v a 2 s.c  om*/
 * @return a random value according to the validation constraint
 */
public static Object getRandomValue(final Field field) {

    Class<?> fieldType = field.getType();

    Object result = null;

    if (field.isAnnotationPresent(AssertFalse.class)) {
        result = false;
    }
    if (field.isAnnotationPresent(AssertTrue.class)) {
        result = true;
    }
    if (field.isAnnotationPresent(Null.class)) {
        result = null;
    }
    if (field.isAnnotationPresent(Future.class)) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, ConstantsUtil.DEFAULT_DATE_RANGE);
        result = new DateRangeRandomizer(new Date(), calendar.getTime()).getRandomValue();
    }
    if (field.isAnnotationPresent(Past.class)) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -ConstantsUtil.DEFAULT_DATE_RANGE);
        result = new DateRangeRandomizer(calendar.getTime(), new Date()).getRandomValue();
    }
    if (field.isAnnotationPresent(Max.class)) {
        Max maxAnnotation = field.getAnnotation(Max.class);
        long maxValue = maxAnnotation.value();
        result = MaxValueRandomizer.getRandomValue(fieldType, maxValue);
    }
    if (field.isAnnotationPresent(DecimalMax.class)) {
        DecimalMax decimalMaxAnnotation = field.getAnnotation(DecimalMax.class);
        BigDecimal decimalMaxValue = new BigDecimal(decimalMaxAnnotation.value());
        result = MaxValueRandomizer.getRandomValue(fieldType, decimalMaxValue.longValue());
    }
    if (field.isAnnotationPresent(Min.class)) {
        Min minAnnotation = field.getAnnotation(Min.class);
        long minValue = minAnnotation.value();
        result = MinValueRandomizer.getRandomValue(fieldType, minValue);
    }
    if (field.isAnnotationPresent(DecimalMin.class)) {
        DecimalMin decimalMinAnnotation = field.getAnnotation(DecimalMin.class);
        BigDecimal decimalMinValue = new BigDecimal(decimalMinAnnotation.value());
        result = MinValueRandomizer.getRandomValue(fieldType, decimalMinValue.longValue());
    }
    if (field.isAnnotationPresent(Size.class)) {
        Size sizeAnnotation = field.getAnnotation(Size.class);
        int minSize = sizeAnnotation.min();
        int maxSize = sizeAnnotation.max();
        result = RandomStringUtils.randomAlphabetic(new RandomDataGenerator().nextInt(minSize, maxSize));
    }
    return result;

}

From source file:com.braffdev.server.core.container.injection.DependencyInjector.java

/**
 * Determines the list of fields that need to be injected.
 *
 * @param target the object.//from   w w  w  .  j a  v  a  2 s  .  co m
 * @return the list of fields.
 */
private static List<Field> getFields(Object target) {
    List<Field> fields = new ArrayList<Field>();

    Class<?> clazz = target.getClass();
    while (!Object.class.equals(clazz)) {

        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {

            // is the Dependency annotation present?
            if (field.isAnnotationPresent(Dependency.class)) {
                fields.add(field);
            }
        }

        clazz = clazz.getSuperclass();
    }

    return fields;
}

From source file:org.apache.pulsar.common.configuration.PulsarConfigurationLoader.java

/**
 * Validates {@link FieldContext} annotation on each field of the class element. If element is annotated required
 * and value of the element is null or number value is not in a provided (min,max) range then consider as incomplete
 * object and throws exception with incomplete parameters
 *
 * @param object//from w w  w.  j a v a2 s .  c om
 * @return
 * @throws IllegalArgumentException
 *             if object is field values are not completed according to {@link FieldContext} constraints.
 * @throws IllegalAccessException
 */
public static boolean isComplete(Object obj) throws IllegalArgumentException {
    checkNotNull(obj);
    Field[] fields = obj.getClass().getDeclaredFields();
    StringBuilder error = new StringBuilder();
    for (Field field : fields) {
        if (field.isAnnotationPresent(FieldContext.class)) {
            field.setAccessible(true);
            Object value;

            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }

            if (log.isDebugEnabled()) {
                log.debug("Validating configuration field '{}' = '{}'", field.getName(), value);
            }
            boolean isRequired = ((FieldContext) field.getAnnotation(FieldContext.class)).required();
            long minValue = ((FieldContext) field.getAnnotation(FieldContext.class)).minValue();
            long maxValue = ((FieldContext) field.getAnnotation(FieldContext.class)).maxValue();
            if (isRequired && isEmpty(value)) {
                error.append(String.format("Required %s is null,", field.getName()));
            }

            if (value != null && Number.class.isAssignableFrom(value.getClass())) {
                long fieldVal = ((Number) value).longValue();
                boolean valid = fieldVal >= minValue && fieldVal <= maxValue;
                if (!valid) {
                    error.append(String.format("%s value %d doesn't fit in given range (%d, %d),",
                            field.getName(), fieldVal, minValue, maxValue));
                }
            }
        }
    }
    if (error.length() > 0) {
        throw new IllegalArgumentException(error.substring(0, error.length() - 1));
    }
    return true;
}

From source file:com.u2apple.tool.util.AndroidDeviceUtils.java

public static String getPropertyByKey(AndroidDeviceRanking androidDevice, String key) {
    if (androidDevice == null || key == null) {
        return null;
    }/* w ww . j a v a 2 s  .c o  m*/
    for (Field field : androidDevice.getClass().getSuperclass().getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Key.class)) {
            Key keyAnno = field.getAnnotation(Key.class);
            if (keyAnno.value().equals(key)) {
                try {
                    return (String) field.get(androidDevice);
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    Logger.getLogger(AndroidDeviceUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    return null;
}

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

/**
 * //from  w ww.  j a  v a  2 s.com
 * @param alfrescoContent
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ORMException
 */
public static void executeCustomeMethodForProperty(final AlfrescoContent alfrescoContent,
        final BeanFactory beanFactory) throws SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException, ORMException {
    NodeRef nodeRef = getNodeRef(alfrescoContent);
    List<Field> fields = new ArrayList<Field>();
    ReflectionUtil.getFields(alfrescoContent.getClass(), fields);
    for (Field field : fields) {
        if (field.isAnnotationPresent(SetProperty.class)) {
            SetProperty setProperty = field.getAnnotation(SetProperty.class);
            if (StringUtils.isNotEmpty(setProperty.setPropertMethodName())) {
                Object target = getTargetServiceBean(setProperty.springBeanID(), beanFactory);
                Method customeMethod = target.getClass().getMethod(setProperty.setPropertMethodName(),
                        NodeRef.class, AlfrescoORM.class);
                customeMethod.invoke(target, nodeRef, alfrescoContent);
            } else {
                throw new ORMException("Please set cutome method name to set property");
            }
        }
    }
}

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

public static Map<QName, Serializable> getAlfrescoProperty(final AlfrescoORM alfrescoORM)
        throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchMethodException,
        InvocationTargetException, InstantiationException {
    List<Field> fields = new ArrayList<Field>();
    ReflectionUtil.getFields(alfrescoORM.getClass(), fields);
    Map<QName, Serializable> retVal = new HashMap<QName, Serializable>(fields.size());
    for (Field field : fields) {
        if (!field.isAnnotationPresent(SetProperty.class)) {
            if (field.isAnnotationPresent(AlfrescoQName.class)
                    && !field.isAnnotationPresent(AlfrescoAssociation.class)) {
                AlfrescoQName alfrescoQName = field.getAnnotation(AlfrescoQName.class);
                QName qName = QName.createQName(alfrescoQName.namespaceURI(), alfrescoQName.localName());
                Method getterMethod = ReflectionUtil.getMethod(alfrescoORM.getClass(), field.getName());
                retVal.put(qName, (Serializable) getterMethod.invoke(alfrescoORM));
            } else if (field.isAnnotationPresent(AlfrescoAspect.class)) {
                Method getterMethod = ReflectionUtil.getMethod(alfrescoORM.getClass(), field.getName());
                AlfrescoORM aspect = (AlfrescoORM) getterMethod.invoke(alfrescoORM);
                if (null != aspect) {
                    retVal.putAll(getAlfrescoProperty(aspect));
                }//  ww  w .  jav a 2 s  .c o  m
            }
        }
    }
    return retVal;
}

From source file:br.gov.frameworkdemoiselle.util.contrib.Strings.java

public static String toString(Object object) {
    StringBuffer result = new StringBuffer();
    Object fieldValue;//w  ww.  j  a v a2 s .com

    if (object != null) {
        result.append(object.getClass().getSimpleName());
        result.append(" [");

        boolean first = true;
        for (Field field : Reflections.getNonStaticDeclaredFields(object.getClass())) {
            if (!field.isAnnotationPresent(Ignore.class)) {
                if (first) {
                    first = false;
                } else {
                    result.append(", ");
                }

                result.append(field.getName());
                result.append("=");
                fieldValue = Reflections.getFieldValue(field, object);
                result.append(fieldValue != null && fieldValue.getClass().isArray()
                        ? Arrays.toString((Object[]) fieldValue)
                        : fieldValue);
            }
        }

        result.append("]");
    }

    return result.toString();
}

From source file:com.shrj.util.ReflectionUtils.java

public static String getAnnotatedFieldName(Class clazz, Class<? extends Annotation> annotation) {
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (field.isAnnotationPresent(annotation)) {
            return field.getName();
        }//from   w ww  . ja  va 2s  . c  om
    }
    return null;
}