Search code examples
javaspring-annotations

How to get @Attribute name?


I have this annotated java class and would like to get the name from @Attribute(name = "HSS-EsmApnId") and then get the value from the following String to make a Map.

import java.util.List;

import javax.naming.Name;

import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;

@Entry(objectClasses = {"HSS-EsmApn"}, base = "nodeName=jambala")
public final class Apn {

    @Id
    private Name dn;

    @Attribute(name = "HSS-EsmApnId") // this name would be the key
    private String apnId; // and apnId would be the value

    @Attribute(name = "HSS-EsmApnName")
    private String apnName;

    @Attribute(name = "groupId")
    private String groupId;

    @Attribute(name = "objectClass")
    private List<String> objectClass;

    @Attribute(name = "ownerId")
    private String ownerId;

    @Attribute(name = "permissions")
    private String permissions;

    @Attribute(name = "shareTree")
    private String shareTree;

    @Override
    public String toString() {
        return "Apn [dn=" + dn + ", apnId=" + apnId + ", apnName=" + apnName + ", groupId=" + groupId + ", objectClass="
            + objectClass + ", ownerId=" + ownerId + ", permissions=" + permissions + ", shareTree=" + shareTree
            + "]";
    }
}

I've tried to use Annotation but I am only able to get the @Entry annotation values.

    Class<?> clazz = Apn.class;
    System.out.println(clazz);

    java.lang.annotation.Annotation[] annotations = clazz.getAnnotations();
    for (Annotation annotation : annotations) {
        System.out.println(annotation.annotationType());
    }

Any help much appreciated.


Solution

  • You are asking for class level annotations. What you want to do, is get field level annotations:

    Field field = Apn.class.getDeclaredField("apnId");
    Annotation[] annotations = field.getAnnotations();
    

    Also, if you want to get specific annotation, you can use field.getAnnotationsByType(Entry.class), which would give you access to the specific class of the annotation and its parameters, such as name, as you need in your case.