How to access package level annotations in runtime.java from jar?

How can I access all classes of package information in the bank in my class? I want to access the package level annotations used in these classes.

I want to take the following steps: -

  • Find all classes in package-info.java
  • Get their packages
  • Get annotation @PackageOwner
+4
source share
3 answers

guava 14+ came to the rescue :)

the following code works

public class OwnerFinder {
    public static void main(String[] args) {
        try {
            ClassPath classPath = ClassPath.from(OwnerFinder.class.getClassLoader());
            classPath.getTopLevelClassesRecursive("com.somepackage")
                    .stream()
                    .filter(c -> c.getSimpleName().equals("package-info"))
                    .map(c -> c.load().getPackage().getAnnotation(PackageOwner.class))
                    .forEach(a -> System.out.println(a.owner()));

        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

applying annotation below for package-info.java

@PackageOwner(owner = "shaikhm")
package com.somepackage;
+5
source

, api. Package , , . , getAnnotations() :

import java.lang.annotation.Annotation;

public class PackageAnnotationsTest {

    public static void main(String[] args) {
        Package myPackage = AClassInMyPackage.class.getPackage();
        Annotation[] myPackageAnnotations = myPackage.getAnnotations();
        System.out.println("Available annotations for package : " + myPackage.getName());
        for(Annotation a : myPackageAnnotations) {
            System.out.println("\t * " + a.annotationType());
        }
    }
}

+5

Perhaps you could try the reflection library .

https://github.com/ronmamo/reflections

A typical use of reflections would be:

Reflections reflections = new Reflections("my.project");

Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);
+1
source

Source: https://habr.com/ru/post/1616369/


All Articles