How can i access all package-info classes in a jar in my class path ? I want to access the package level annotations used in these classes.
I want to do the following steps:-
package-info. java is a way to apply java annotations at the package level. In this case Jaxb is using package-level annotations to indicate the namespace, and to specify namespace qualification for attributes (source). Follow this answer to receive notifications.
The package-info. java is a Java file that can be added to any Java source package. It is used to provide info at a "package" level as per its name. It contains documentation and annotations used in the package.
Simply put, package-info is a Java file that can be added to any Java package.
package level access is the default access level provided by Java if no access modifier is specified. These access modifiers are used to restrict the accessibility of a class, method, or variable on which it applies.
There's a more simple solution, not involving an external api. You can get the Package object from a class located in the package for which you want the annotations. And then get these annotations by calling the method getAnnotations() on the package :
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());
}
}
}
Thanks to this link that helped me on this question. I had first read this thread and Parikshit's answer but I didn't want to use an external api.
guava 14+ came to the rescue :)
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();
}
}
}
application of the annotation is below for the package-info.java
@PackageOwner(owner = "shaikhm")
package com.somepackage;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With