How to get Annotation name using Java

Viewed 134

I'm using the method below to get the names of all getter methods of a class:

 private static Map<String, Object> fetchGetterMethods(Object object) {
        Map<String, Object> result = new HashMap<String, Object>();
        BeanInfo info;
        try {
            info = Introspector.getBeanInfo(object.getClass());
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                Method reader = pd.getReadMethod();
                if (reader != null) {
                    String name = pd.getName();
                    if (!"class".equals(name)) {
                        try {
                            Object value = reader.invoke(object);
                            result.put(name, value);
                        } catch (Exception e) {
                            
                        }
                    }
                }
            }
        } catch (IntrospectionException e) {
            
        } finally {
            return result;
        }

    }

I would like to skip the getter methods annotated with @Transient. How can I implement this?

 @Transient
 public boolean isValid() {
 }
2 Answers

You should use the Method#isAnnotationPresent method.

if (!reader.isAnnotationPresent(Transient.class)) {
    // do work
}

This is a convenience method for the solution suggested by @rzwitserloot, and is the equivalent to:

if (reader.getAnnotation(Transient.class) == null) {

All you need is reader.getAnnotation(Transient.class) - if that returns something (it'll be an instance of Transient), it had the annotation. If it returns null, it did not. You can only do this to annotations whose definition is explicitly annotated with retentionlevel runtime, but assuming you're talking about JPA's @Transient, it is.

Note that writing a return statement in a finally block is absolutely not something you want to do.

Related