注释的处理发生在哪里?

发布于 2024-12-29 17:52:46 字数 358 浏览 0 评论 0 原文

我最近一直在阅读有关注释的内容,我有点困惑。我使用了注释 @NotNull 但我真的不知道它如何检查变量是否不为空。我在代码中没有看到任何检查 null 值的内容。这是有道理的,因为它是一个接口,那么实际处理发生在哪里以及为什么代码中没有指定这个位置?我见过的例子通常只是做一个接受值的注释,但不做任何其他事情,所以我对实现发生在哪里感到困惑。

I've been reading about annotations lately, and I'm a bit confused. I've used the annotation @NotNull but I don't really know how it checks if the variable is not null. No where in the code do I see anything checking values for null. That makes sense because it's an interface, so where does the actual processing happen and why isn't this location specified in the code? The examples I've seen usually just make an annotation that takes values, but doesn't do anything else, so I'm confused as to where the implementation occurs.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光的暖冬 2025-01-05 17:52:46

注释只是一种元数据,不多也不少。
当您想要指定有关该类的一些详细信息时,您可以在其上添加注释。
(在某种程度上)将它们视为定义元数据的旧的众所周知的 XML 方法的替代方法。

现在,很明显有人读取了您的 XML 并运行了使用元数据进行某些操作的代码。注释也会发生同样的情况:注释所属的框架负责读取注释并利用这些信息进行某些操作。以@NotNull 为例,它的 hibernate-validator 项目。 java 公开的 API 允许通过反射访问注释中的信息(例如 java.lang.ClassMethodField 等类,等等)。因此,在 hibernate 验证器内部的某处,有一段代码会进入您的类,通过反射读取注释并检查该类是否遵守这些注释。
这些注释通常具有“运行时”保留策略,这意味着它们保留在字节码中并与带有这些注释的类一起加载。

还有一些注释需要由 Java 编译器处理。如@Deprecated、@SuppressWarnings等。有这样的注解的好处是可以在编译阶段发现一些代码问题。

您还可以放置注释处理器并在编译阶段“插入”它们,但情况完全不同。

希望这能澄清一点注释的用法

Annotation is just a metadata, no more no less.
When you want to specify some details about the class you put annotations on it.
Think about them (to some extent) as an alternative to the old well known XML way to define metadata.

Now, its obvious that someone reads your XML and runs the code that makes something with the metadata. The same happens with annotations: a framework to which annotation belongs to is responsible to read the annotation and make something with this information. In the case of @NotNull, its hibernate-validator project. The API exposed by java allows to access the information in the annotations by reflection (the classes like java.lang.Class, Method, Field, and so on). So somewhere inside hibernate validator there is a code that goes to your class, reads the annotations by reflection and checks whether the class adheres these annotations.
These annotation usually have retention policy 'runtime' which means that they're preserved in the bytecode and loaded along with the class that carries these annotations.

There are also annotations that should be processed by Java compiler. Like @Deprecated, @SuppressWarnings and so on. The benefit of having such annotation is that you can find some code issues during the compilation phase.

You can also put the annotation processors and 'plug' them during the compilation phase, buts its entirely different story.

Hope this clarifies a little the usage of annotations

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文