Java运行时保留注释 - 编译时需要注释类,但在运行时不需要注释类? [英] Java runtime retention annotations - annotation class required at compile time but not at runtime?

查看:876
本文介绍了Java运行时保留注释 - 编译时需要注释类,但在运行时不需要注释类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出使用运行时级别保留注释注释的类的编译时间和运行时类路径的确切效果,例如:@ javax.inject.Named。这是我到目前为止的理解:

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. javax.inject.Named类必须在类路径的编译时出现。

  2. 然后将其作为元数据编译为字节码,并可在运行时通过Reflections API获取并进行相应处理;但是,这个类不需要存在于运行时类路径上。

因此,如果我编译一个带有注释的java类的jar @ javax.inject.Named,这个编译好的jar文件既可以在容器(即Jboss)中运行,也可以在从命令行启动的普通旧JVM中运行(不需要额外的类路径)。但是,如果我将这个源代码提供给一个项目,该项目将与javac一起编译(并且没有其他类路径),它将不再正确编译?如果这个假设是正确的,如果我需要在可能或可能不在容器中运行的项目(即Jboss)之间共享已编译的二进制文件和源文件,这似乎有点限制。

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).

如果是这种情况,我是否需要创建一个包装对象(用@ javax.inject.Named注释),该对象委托给内部的非注释对象?是另一个在编译时禁用注释处理的选项吗?请参阅 http://docs.oracle.com/ javase / 7 / docs / technotes / tools / solaris / javac.html #process

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

推荐答案

您需要注释要出现在编译类路径中以使用注释编译源文件。您不需要在类路径中使用注释使用编译的类B编译类A.

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.

许多开源库(例如Guava或DbSetup)例如,使用javax.annotation或Findbugs注释,但您不需要在类路径中使用这些注释来编译(并运行)依赖于这些库的源代码。

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.

这篇关于Java运行时保留注释 - 编译时需要注释类,但在运行时不需要注释类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆