Cork Kochi
Cork Kochi

Reputation: 1891

How to get Annotation name using Java

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() {
 }

Upvotes: 3

Views: 303

Answers (2)

blacktide
blacktide

Reputation: 12156

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) {

Upvotes: 4

rzwitserloot
rzwitserloot

Reputation: 103803

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.

Upvotes: 4

Related Questions