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.palantir.ptoss.util.Reflections.java

/**
 * Returns the list of fields on this class annotated with the passed {@link Annotation}
 * @param klass checks the {@link Field}s on this class
 * @param annotation looks for this {@link Annotation}
 * @return list of all {@link Field}s that are annotated with the specified {@link Annotation}
 *///w w w.  j  a  v a2s.co m
public static List<Field> getAnnotatedFields(Class<?> klass, Class<? extends Annotation> annotation) {
    List<Field> annotatedFields = Lists.newArrayList();
    for (Field f : klass.getDeclaredFields()) {
        if (f.isAnnotationPresent(annotation)) {
            annotatedFields.add(f);
        }
    }
    return annotatedFields;
}

From source file:com.rockagen.commons.util.ClassUtil.java

/**
 * obtain fields list of specified class and which are annotated by incoming
 * annotation class If recursively is true, obtain fields from all class
 * hierarchy/*from w  ww .j  av  a2  s  . c  o m*/
 * 
 * @param clazz class
 *            - where fields are searching
 * @param annotationClass
 *            - specified annotation class
 * @param recursively
 *            param
 * @return list of annotated fields
 */
public static Field[] getAnnotatedDeclaredFields(Class<?> clazz, Class<? extends Annotation> annotationClass,
        boolean recursively) {
    Field[] allFields = getDeclaredFields(clazz, recursively);
    List<Field> annotatedFields = new LinkedList<Field>();

    for (Field field : allFields) {
        if (field.isAnnotationPresent(annotationClass))
            annotatedFields.add(field);
    }

    return annotatedFields.toArray(new Field[annotatedFields.size()]);
}

From source file:org.bigmouth.nvwa.utils.xml.Dom4jEncoder.java

private static void addElement(String itemNodeName, Element parent, Object obj) {
    Class<?> cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();
    Element item = (StringUtils.isNotBlank(itemNodeName)) ? parent.addElement(itemNodeName) : parent;
    for (Field field : fields) {
        String name = field.getName();
        String nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(name), "_").toLowerCase();
        if (field.isAnnotationPresent(Argument.class)) {
            nodename = field.getAnnotation(Argument.class).name();
        }//from w  ww . j a  v a  2  s.  c  om
        Element node = item.addElement(nodename);

        String invokeName = StringUtils.join(new String[] { "get", StringUtils.capitalize(name) });
        try {
            Object value = MethodUtils.invokeMethod(obj, invokeName, new Object[0]);

            if (null != value) {
                if (value instanceof String || value instanceof Double || value instanceof Float
                        || value instanceof Long || value instanceof Integer || value instanceof Short
                        || value instanceof Byte || value instanceof Boolean) {
                    node.setText(value.toString());
                } else {
                    addElement(null, node, value);
                }
            }
        } catch (NoSuchMethodException e) {
            LOGGER.warn("NoSuchMethod-" + invokeName);
        } catch (IllegalAccessException e) {
            LOGGER.warn("IllegalAccess-" + invokeName);
        } catch (InvocationTargetException e) {
            LOGGER.warn("InvocationTarget-" + invokeName);
        }
    }
}

From source file:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Checks a request parameter name against all possible {@link Model} attributes, converting it to
 *   the appropriate repository field name for querying and sorting.
 *
 * @param param/*w w  w.  j  av  a2 s  . c  om*/
 * @return
 */
public static String remapParameterName(String param, Class<? extends Model<?>> model) {
    logger.debug(String.format("Attempting to remap query string parameter: %s", param));
    for (Field field : model.getDeclaredFields()) {
        String fieldName = field.getName();
        if (field.isAnnotationPresent(Aliases.class)) {
            Aliases aliases = field.getAnnotation(Aliases.class);
            for (Alias alias : aliases.value()) {
                if (alias.value().equals(param))
                    return fieldName;
            }
        } else if (field.isAnnotationPresent(Alias.class)) {
            Alias alias = field.getAnnotation(Alias.class);
            if (alias.value().equals(param))
                return fieldName;
        }
    }
    logger.debug(String.format("Parameter remapped to: %s", param));
    return param;
}

From source file:com.chrynan.teleport.Teleport.java

/**
 * Retrieves all the Field objects that have a Data annotation within the binding object class.
 *
 * @param bindingObject The object to search for Data annotated Fields.
 * @return List<Field> The list of annotated Fields; returns an empty list if there are no Fields.
 *///from  w w w.  j  a  v  a 2s. co m
private static final List<Field> getAnnotatedFields(Object bindingObject) {
    List<Field> fields = new ArrayList<>();
    for (Field f : bindingObject.getClass().getDeclaredFields()) {
        if (f.isAnnotationPresent(Data.class)) {
            f.setAccessible(true);
            fields.add(f);
        }
    }
    return fields;
}

From source file:org.dbg4j.core.DebugUtils.java

/**
 * Method creates <code>Map&lt;String, String&gt;</code> that contains instance field names
 * and their values. By default parameter value evaluates by {@link DefaultEvaluationAdapter} unless another
 * evaluator is set by {@link Adapter} annotation.
 *
 * @param instance//from www  .  j  a v a2 s  .c o m
 * @param fieldsForDebug
 * @return
 */
@Nonnull
public static Map<String, String> getFieldValues(@Nonnull Object instance,
        @Nonnull Collection<Field> fieldsForDebug) {
    Map<String, String> result = new HashMap<String, String>();

    for (Field field : fieldsForDebug) {
        String fieldValue = DefaultDebuggingAdapter.UNKNOWN_VALUE;
        try {
            EvaluationAdapter evaluationAdapter = null;
            if (field.isAnnotationPresent(Adapter.class)) {
                Adapter adapterAnnotation = field.getAnnotation(Adapter.class);
                evaluationAdapter = adapterAnnotation.value().newInstance();
            }
            if (evaluationAdapter == null) {
                evaluationAdapter = new DefaultEvaluationAdapter();
            }

            if (Modifier.isStatic(field.getModifiers())) {
                fieldValue = evaluationAdapter.evaluate(field.getDeclaringClass(),
                        FieldUtils.readDeclaredStaticField(instance.getClass(), field.getName(), true));
            } else {
                fieldValue = evaluationAdapter.evaluate(field.getDeclaringClass(),
                        FieldUtils.readDeclaredField(instance, field.getName(), true));
            }
        } catch (Exception ignored) {
        }
        result.put(field.getName(), fieldValue);
    }

    return result;
}

From source file:org.agiso.core.lang.util.ObjectUtils.java

/**
 * Metoda generujca reprezentacj acuchow obiektu. Przeglda wszystkie
 * pola obiektu i pobiera ich reprezentacj acuchow. Na tej podstawie
 * generuje acuch wynikowy./*from   ww  w  .ja va2s . c om*/
 * 
 * @param clazz
 * @param object
 */
private static void toStringObject(Class<?> clazz, Object object) {
    StringBuffer buffer = (StringBuffer) ThreadUtils.getAttribute(TOSTRING_TCBUFF);

    String hexHash = Integer.toHexString(System.identityHashCode(object));
    if (0 == buffer.length()) {
        buffer.append(clazz.getSimpleName()).append('@').append(hexHash).append(TOSTRING_PREFIX);
    }

    @SuppressWarnings("unchecked")
    Set<String> converted = (Set<String>) ThreadUtils.getAttribute(TOSTRING_TCATTR);
    converted.add(object.getClass().getCanonicalName() + "@" + hexHash);

    // Rekurencyjne przegldanie wszystkich klas nadrzdnych:
    Class<?> superClass = clazz.getSuperclass();
    if (superClass != null) {
        toStringObject(superClass, object);
    }

    String hyphen = "";
    if (TOSTRING_PREFIX.charAt(0) != buffer.charAt(buffer.length() - 1)) {
        hyphen = TOSTRING_HYPHEN;
    }

    for (Field field : clazz.getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.isAnnotationPresent(InToString.class)) {
                InToString inToString = field.getAnnotation(InToString.class);
                if (!inToString.ignore()) {
                    String name = inToString.name();
                    buffer.append(hyphen).append((name.length() > 0) ? name : field.getName())
                            .append(TOSTRING_COLON);
                    toStringField(field.get(object));
                    hyphen = TOSTRING_HYPHEN;
                }
            } else if ((field.getModifiers() & (Modifier.STATIC | Modifier.FINAL)) == 0) {
                buffer.append(hyphen).append(field.getName()).append(TOSTRING_COLON);
                toStringField(field.get(object));
                hyphen = TOSTRING_HYPHEN;
            }
        } catch (Exception e) {
            // TODO: Zaimplementowa logowanie wyjtku
            e.printStackTrace();
        }
    }
}

From source file:ee.ria.xroad.common.message.SoapUtils.java

/**
 * Checks consistency of two SOAP headers.
 * @param h1 the first SOAP header//from ww  w  . j  a v a2s. c  o m
 * @param h2 the second SOAP header
 */
public static void checkConsistency(SoapHeader h1, SoapHeader h2) {
    for (Field field : SoapHeader.class.getDeclaredFields()) {
        if (field.isAnnotationPresent(CheckConsistency.class)) {
            Object value1 = getFieldValue(field, h1);
            Object value2 = getFieldValue(field, h2);
            if (ObjectUtils.notEqual(value1, value2)) {
                throw new CodedException(X_INCONSISTENT_HEADERS,
                        "Field '%s' does not match in request and response", field.getName());
            }
        }
    }
}

From source file:bdi4jade.util.ReflectionUtils.java

/**
 * Sets plan body fields annotated with {@link bdi4jade.annotation.Belief}.
 * /*w  w  w.  j  a v a2 s.co  m*/
 * @param planBody
 *            the plan body to be setup with beliefs.
 */
public static void setupBeliefs(PlanBody planBody) {
    Capability capability = planBody.getPlan().getPlanLibrary().getCapability();
    Class<?> currentClass = planBody.getClass();
    while (PlanBody.class.isAssignableFrom(currentClass)) {
        for (Field field : currentClass.getDeclaredFields()) {
            boolean b = field.isAccessible();
            field.setAccessible(true);
            try {
                if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                    if (Belief.class.isAssignableFrom(field.getType())) {
                        bdi4jade.annotation.Belief beliefAnnotation = field
                                .getAnnotation(bdi4jade.annotation.Belief.class);
                        String beliefName = beliefAnnotation.name();
                        if (beliefName == null || "".equals(beliefName)) {
                            beliefName = field.getName();
                        }
                        Belief<?, ?> belief = capability.getBeliefBase().getBelief(beliefName);
                        field.set(planBody, belief);
                    } else {
                        throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                    }
                }
            } catch (Exception exc) {
                log.warn(exc);
            }
            field.setAccessible(b);
        }
        currentClass = currentClass.getSuperclass();
    }
}

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

/**
 * Get a field name (object attribute name) or the value of @Name if
 * annotation is present. In other words, if @Name is present returns
 * field.getAnnotation(Name.class).value(), otherwise field.getName();
 * //from  ww  w  .j a v  a  2s. c o m
 * @param field
 * @return @Name annotation value or object attribute name;
 */
public static String getFieldName(Field field) {
    if (field.isAnnotationPresent(Name.class)) {
        String name = field.getAnnotation(Name.class).value();
        if (name == null || name.trim().isEmpty())
            throw new EntryException("Annotation @Name must have a value");
        return name;
    } else
        return field.getName();
}