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

查看:36
本文介绍了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 获取并进行相应处理;但是,此类不需要存在于运行时类路径中.

因此,如果我用 @javax.inject.Named 注释的 java 类编译一个 jar,这个编译的 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#processing

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天全站免登陆