简体   繁体   中英

How to get annotations name atributes?

I have a class named ClBranch.java like below:

    @Entity
    @Table(name = "PROVINCE")
    public class PROVINCE implements Serializable {
        @Id
        @Column(name="PR_CODE", length = 50) 
        private String provinceCode

        @Column(name="PR_NAME", length = 500) 
        private String provinceName
    ......
    getter-setter.
    }


This is my code:
    public static String getClassAnnotationValue(Class classType, Class annotationType, String attributeName) {
            String value = null;

            Annotation annotation = classType.getAnnotation(annotationType);
            if (annotation != null) {
                try {
                    value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            return value;
        }


 String columnName = getClassAnnotationValue(PROVINCE .class, Column.class, "name");    

By this way, I only get ColumnName as PROVINCE. I can not get ColumnName. How can I do it?

The @Column annotation is defined on the fields, not on the class. So you must query annotation values from the private fields:

String columnName = getAnnotationValue(PROVINCE.class.getDeclaredField("provinceCode"), Column.class, "name");

To be able to pass Field objects to your method, change the type of your classType parameter from Class to AnnotatedElement . Then you can pass classes, fields, parameters or methods:

public static String getAnnotationValue(AnnotatedElement element, Class annotationType, String attributeName) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM