mardi 3 janvier 2017

How to read annotation which is declared over a Java object?

How to read annotation which is declared over an object.

For e.g

Annotation :

AuthorInfo.java

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AuthorInfo {
    String author() default "Dushyant Kumar";
    String login() default "dushyantashu";
}

What I am trying to do :

Book.java

@Data
public class Book {
    private int serialNo;
    private String review;
}

Main.java

public class Main {

    @AuthorInfo (
            author = "Barry Allen",
            login = "theflash"
    )
    private static Book book = new Book();

    public static void main(String[] args) {
        showAnnotation(book);
    }

    private static void showAnnotation(Object object) {
        // How to get values of annotation declared over this object. 
    }
}

My usecase is to generate this generic showAnnotation() method, that's why param is Object. How to achieve this? From what I explored, I only got ways to read annotation if it's declared over a class, or declared over a member of a class. Isn't there a way where given an object, if some annotation is present over it can be read?

Thanks





Aucun commentaire:

Enregistrer un commentaire