mercredi 29 avril 2020

Cannot get custom annotations from Java class

I want to get class level annotation from Java class:

    class FixAnnotation {

        public String[] author;

    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface Fix {

        public String[] author() default "";

    }

I tried this example of compiled java class:

@Component("test")
@Fix(
    author = {"Example author 1", "Example author 2"}
)
public class Order implements Action {
..
}

But when I try:

public List listLocalFilesAndDirsAllLevels(File baseDir) {

        List<File>  collectedFilesAndDirs = new ArrayList<>();
        Deque<File> remainingDirs = new ArrayDeque<>();

        if(baseDir.exists()) {
            remainingDirs.add(baseDir);

            while(!remainingDirs.isEmpty()) {
                File dir = remainingDirs.removeLast();
                List<File> filesInDir = Arrays.asList(dir.listFiles());
                for(File fileOrDir : filesInDir)  {
                    // We need to process only .class files
                    if(fileOrDir.getName().endsWith(".class")){
                        collectedFilesAndDirs.add(fileOrDir);
                        if(fileOrDir.isDirectory()) {
                            remainingDirs.add(fileOrDir);
                        }
                    }
                }
            }
        }

        return collectedFilesAndDirs;
    }

      List<File> list;

      for(int i=0; i<list.size(); i++) {
            File item = list.get(i);
            System.out.println(item.getName());

            Fix name = item.getClass().getAnnotation(Fix.class);

            out.println("author: " + name.author());
       }

I get NPE. Do you know how I can get the annotation content?





Aucun commentaire:

Enregistrer un commentaire