Bndtools - Import-Package declaration for references to static fields in OSGi
Anyone who works with bndtools, knows that it calculates Package-Import declarations for the manifest. This is a great feature, because one wouldn’t do this by hand.
In case use references to static fields e.g. for constants with primitive types, the compiler replaces the constant name with the constant value at compile time.
Because of that example it is is not always possible for build tools like bndtools to determine the origin. Despite that, wouldn’t it be good, to define the Import-Package, because there is dependency relation to the other class?
It is possible in OSGi using the org.osgi.annotation.bundle.Referenced
annotation. It is a build time annotation to instruct tools like bndtools to create the additional Import-Package declarations. The annotation can be found it the bundle annotation bundle at Maven Central:
org.osgi:org.osgi.annotation.bundle:2.0.0
You can simply put the annotation at a class, that uses a static reference. As annotation parameter you can then provide the Java-class that hold the static constant.
@Referenced(MyClass.class)
public class Example {
public void myMethod() {
System.out.println(MyClass.TEXT);
}
...
This annotation makes it possible to define import package requirements to other bundles in a declarative way. So the resolver can know the real dependency to the other bundles, even if the a build tool can not detect this dependency for technical reasons.
Cheers!
by Mark Hoffmann