简体   繁体   中英

Java runtime retention annotations - annotation class required at compile time but not at runtime?

I am trying to figure out the exact effects in regards to compile time and runtime classpaths of a class annotated with a runtime level retention annotation, for example: @javax.inject.Named. This is my understanding so far:

  1. The javax.inject.Named class must be present at compile time on the classpath.
  2. This is then compiled into the bytecode as meta-data and can be obtained at runtime via the Reflections API and processed accordingly; however, this class DOES NOT need to exist on the runtime classpath.

Thus, if I compile a jar with a java class annotated with @javax.inject.Named, this compiled jar file can be run both in a container (ie Jboss) and in a plain old JVM launched from the command line (with no additional classpath entires). However, if I make this source code available to a project that will be compiled along with it just using javac (and no additional classpath entires), it will no longer compile correctly? If this assumption is correct, this seems to be a little limiting if I need to share both compiled binaries and source files amongst projects that may or may not be running in a container (ie Jboss).

If this is the case, would I need to create a wrapper object (annotated with @javax.inject.Named) that delegates to the inner, non-annotated object? Is another option to disable annotation processing at compile time? See http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.html#processing

You need the annotation to be present in the compile classpath to compile source files using the annotation. You don't need it in the classpath to compile a class A using a compiled class B using the annotation.

Many open-source libraries (like Guava or DbSetup for example) use the javax.annotation or Findbugs annotations for example, but you don't need to have those annotations in the classpath to compile (and run) your own source code relying on these libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM