Check if a bean field or its accessor method has an annotation - Java java.lang.annotation

Java examples for java.lang.annotation:Field Annotation

Description

Check if a bean field or its accessor method has an annotation

Demo Code


//package com.java2s;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Main {
    /**//from  w w w.j av a  2s  .  c  o m
     * Check if a bean field
     * or its accessor method
     * has an annotation
     * @param pd
     * @param annotations
     * @return
     */
    public static boolean fieldOrPropertyAnnotated(PropertyDescriptor pd,
            Class<? extends Annotation>... annotations) {
        // What to return
        boolean has = false;

        try {
            // Get the getter... oh yeah!
            Method readMethod = pd.getReadMethod();

            Class<?> declaringClass = readMethod.getDeclaringClass();

            // Get the field for the property
            Field field = declaringClass.getDeclaredField(pd.getName());

            // Check each annotation
            for (Class<? extends Annotation> annotation : annotations) {
                if (readMethod.isAnnotationPresent(annotation)
                        || field.isAnnotationPresent(annotation)) {
                    has = true;
                    break;
                }
            }

        } catch (SecurityException e) {
            throw new RuntimeException(String.format(
                    "Can't access field %s in class %s", pd.getName(), pd
                            .getReadMethod().getDeclaringClass()), e);
        } catch (NoSuchFieldException e) {
            throw new IllegalArgumentException(String.format(
                    "Can't find field %s in class %s", pd.getName(), pd
                            .getReadMethod().getDeclaringClass()), e);
        }
        return has;
    }
}

Related Tutorials