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:gr.abiss.calipso.tiers.specifications.GenericSpecifications.java

/**
 * Get an appropriate predicate factory for the given field class
 * @param field/*w  w w  . j  a va  2s  .c om*/
 * @return
 */
private static IPredicateFactory<?> getPredicateFactoryForClass(Field field) {
    Class clazz = field.getType();
    if (clazz.isEnum()) {
        return new EnumStringPredicateFactory(clazz);
    } else if (Persistable.class.isAssignableFrom(clazz)) {
        if (field.isAnnotationPresent(CurrentPrincipal.class)) {
            return currentPrincipalPredicateFactory;
        } else {
            return anyToOnePredicateFactory;
        }
    } else {
        return factoryForClassMap.get(clazz);
    }
}

From source file:com.github.gekoh.yagen.util.FieldInfo.java

public static AccessibleObject getIdFieldOrMethod(Class entityClass) {
    for (Field field : entityClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(Id.class)) {
            return field;
        }// w ww  . j  a  v  a  2  s.  c  o  m
    }
    for (Method method : entityClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(Id.class)) {
            return method;
        }
    }
    return entityClass.getSuperclass() != null ? getIdFieldOrMethod(entityClass.getSuperclass()) : null;
}

From source file:com.serli.chell.framework.form.FormStructure.java

private static boolean isFormField(Field field, Class<?> fieldType) {
    return ((field.getModifiers() & (Modifier.STATIC | Modifier.FINAL)) == 0) && (fieldType.equals(String.class)
            || fieldType.equals(String[].class) && !field.isAnnotationPresent(HtmlTransient.class));
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

private static <T> T getEntryObject(String dn, Map<String, Object> map, Class<T> clazz, boolean cascade) {
    T entry = Beans.getReference(clazz);
    Field[] fields = getSuperClassesFields(entry.getClass());
    for (Field field : fields) {
        if (field.isAnnotationPresent(Ignore.class) || field.isAnnotationPresent(RemoveOnMerge.class))
            continue;

        if (field.isAnnotationPresent(ParentDN.class)) {
            setFieldValue(field, entry, new String[] { getParentDN(dn) });
            continue;
        }/*  w  w w. java 2 s  .c o  m*/

        if (field.isAnnotationPresent(DistinguishedName.class)) {
            setFieldValue(field, entry, new String[] { dn });
            continue;
        }

        String fieldName = getFieldName(field);
        if (map.containsKey(fieldName))
            setFieldValue(field, entry, map.get(fieldName), cascade);
    }
    return entry;
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

/**
 * Convert @LDAPEntry annotated object to Map(String, Object). The valid
 * types for Object Map value is String, String[] or byte[]
 * //from   w w  w .  j  a  v a  2  s.c  o  m
 * @param entry
 * @return Entry Map
 */
public static Map<String, Object> getObjectMap(Object entry) {
    isAnnotationPresent(entry.getClass(), LDAPEntry.class, true);
    Map<String, Object> map = new HashMap<String, Object>();

    Field[] fields = getSuperClassesFields(entry.getClass());
    for (Field field : fields) {
        if (field.isAnnotationPresent(DistinguishedName.class) || field.isAnnotationPresent(Ignore.class)
                || field.isAnnotationPresent(ParentDN.class))
            continue;
        // Ignore override attributes
        if (map.containsKey(getFieldName(field)))
            continue;
        Object value = Reflections.getFieldValue(field, entry);
        if (value == null)
            continue;
        if (field.isAnnotationPresent(RemoveOnMerge.class)) {
            map.put("@RemoveOnMerge", value);
            Reflections.setFieldValue(field, entry, null);
            continue;
        }
        map.put(getFieldName(field), getObjectAsSupportedType(value));
    }
    return map;
}

From source file:com.wit.android.support.fragment.util.FragmentAnnotations.java

/**
 * Sets a view obtained by the given <var>id</var> from the given <var>root</var> view as value
 * the the given <var>field</var>.
 *
 * @param field           A field to which should be obtained view set as value.
 * @param fieldParent     A context in which is the passed view <var>field</var> presented.
 * @param root            A root view of the given context.
 * @param onClickListener An instance of OnClickListener which should be set to injected view
 *                        if {@link com.wit.android.support.fragment.annotation.InjectView#clickable() @InjectView.clickable()}
 *                        flag is set to {@code true}.
 * @return {@code True} when view obtained from the given root view by id presented within
 * annotation placed above the given field was successfully set to that field, {@code false}
 * if such a view was not found or the given field does not have InjectView or InjectView.Last
 * presented./*www.j a v  a2 s  .  c o  m*/
 */
private static boolean injectViewInner(Field field, Object fieldParent, View root,
        View.OnClickListener onClickListener) {
    View view;
    if (field.isAnnotationPresent(InjectView.class)) {
        final InjectView injectView = field.getAnnotation(InjectView.class);
        if ((view = root.findViewById(injectView.value())) != null && attachView(field, fieldParent, view)) {
            if (injectView.clickable()) {
                view.setOnClickListener(onClickListener);
            }
            return true;
        }
    } else if (field.isAnnotationPresent(InjectView.Last.class)) {
        final InjectView.Last injectLastView = field.getAnnotation(InjectView.Last.class);
        if ((view = root.findViewById(injectLastView.value())) != null
                && attachView(field, fieldParent, view)) {
            if (injectLastView.clickable()) {
                view.setOnClickListener(onClickListener);
            }
            return true;
        }
    }
    return false;
}

From source file:com.wit.android.support.fragment.util.FragmentAnnotations.java

/**
 * Injects all annotated field views. Note, that this can run recursively, so it will check all
 * fields for {@link com.wit.android.support.fragment.annotation.InjectView @InjectView} or
 * {@link com.wit.android.support.fragment.annotation.InjectView.Last @InjectView.Last}
 * annotation presented above each of fields of the given <var>classOfRootContext</var>.
 *
 * @param rootContext        A context in which is the passed <var>root</var> view presented and
 *                           into which should be views injected.
 * @param classOfRootContext A class of a context for the current recursive iteration.
 * @param root               A root view of the given context.
 * @param maxSuperClass      If {@code not null}, this method will be called (recursively)
 *                           for all super classes of the given class (max to the specified
 *                           <var>maxSuperClass</var>), otherwise only fields of the given class
 *                           will be iterated.
 * @param onClickListener    An instance of OnClickListener which should be set to injected views
 *                           if {@link com.wit.android.support.fragment.annotation.InjectView#clickable() @InjectView.clickable()}
 *                           flag is set to {@code true}.
 *//*from   w  w  w. j a v a  2  s. c om*/
private static void injectViews(Object rootContext, Class<?> classOfRootContext, View root,
        Class<?> maxSuperClass, View.OnClickListener onClickListener) {
    // Class of fragment must have @InjectViews annotation present to really iterate and inject
    // annotated views.
    if (classOfRootContext.isAnnotationPresent(InjectViews.class)) {
        // Process annotated fields.
        final Field[] fields = classOfRootContext.getDeclaredFields();
        if (fields.length > 0) {
            for (Field field : fields) {
                injectViewInner(field, rootContext, root, onClickListener);
                if (field.isAnnotationPresent(InjectView.Last.class)) {
                    break;
                }
            }
        }
    }

    // Inject also views of supper class, but only to this BaseFragment super.
    final Class<?> superOfRootContext = classOfRootContext.getSuperclass();
    if (superOfRootContext != null && !superOfRootContext.equals(maxSuperClass)) {
        injectViews(rootContext, superOfRootContext, root, maxSuperClass, onClickListener);
    }
}

From source file:br.gov.frameworkdemoiselle.ldap.internal.ClazzUtils.java

public static Field getFieldAnnotatedAs(Class<?> clazz, Class<? extends Annotation> aclazz, boolean required) {
    for (Field field : getSuperClassesFields(clazz))
        if (field.isAnnotationPresent(aclazz))
            return field;
    if (required)
        throw new EntryException(
                "Field with @" + aclazz.getSimpleName() + " not found on class " + clazz.getSimpleName());
    else//from   w  ww  .jav a 2  s . c o m
        return null;
}

From source file:com.hurence.logisland.util.kura.Metrics.java

public static <T> T readFrom(final T object, final Map<String, Object> metrics) {
    Objects.requireNonNull(object);

    for (final Field field : FieldUtils.getFieldsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = field.getAnnotation(Metric.class);
        final boolean optional = field.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Field '%s' is missing metric '%s'", field.getName(), m.value()));
        }/*w  w w .j  a va2s.c  om*/

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            FieldUtils.writeField(field, object, value, true);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to assign '%s' (%s) to field '%s'", value,
                    value.getClass().getName(), field.getName()), e);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    for (final Method method : MethodUtils.getMethodsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = method.getAnnotation(Metric.class);
        final boolean optional = method.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Method '%s' is missing metric '%s'", method.getName(), m.value()));
        }

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            method.invoke(object, value);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to call '%s' (%s) with method '%s'", value,
                    value.getClass().getName(), method.getName()), e);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    return object;
}

From source file:com.ace.erp.common.inject.support.InjectBaseDependencyHelper.java

/**
 * ??//from  w w w. j  av a  2 s . c om
 *
 * @param target
 * @param annotation
 */
private static Set<Object> findDependencies(final Object target, final Class<? extends Annotation> annotation) {

    final Set<Object> candidates = Sets.newHashSet();

    ReflectionUtils.doWithFields(target.getClass(), new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            Object obj = ReflectionUtils.getField(field, target);
            candidates.add(obj);
        }
    }, new ReflectionUtils.FieldFilter() {
        @Override
        public boolean matches(Field field) {
            return field.isAnnotationPresent(annotation);
        }
    });

    ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(method);
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
            candidates.add(ReflectionUtils.invokeMethod(descriptor.getReadMethod(), target));
        }
    }, new ReflectionUtils.MethodFilter() {
        @Override
        public boolean matches(Method method) {
            boolean hasAnnotation = false;
            hasAnnotation = method.isAnnotationPresent(annotation);
            if (!hasAnnotation) {
                return false;
            }

            boolean hasReadMethod = false;
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
            hasReadMethod = descriptor != null && descriptor.getReadMethod() != null;

            if (!hasReadMethod) {
                return false;
            }

            return true;
        }
    });

    return candidates;
}