像@Override 这样的注释在 Java 内部如何工作? [英] How do annotations like @Override work internally in Java?

查看:36
本文介绍了像@Override 这样的注释在 Java 内部如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释注释在 Java 内部是如何工作的?

Can anybody explain to me how annotations work internally in java?

我知道如何使用 java.lang.annotation 库来创建自定义注释.但我仍然不明白它是如何在内部工作的,例如 @Override 注释.

I know how we can create custom annotations by using java.lang.annotation library in java. But I still don't get how it's working internally for example, the @Override annotation.

如果有人能详细解释一下,我将不胜感激.

I will be really thankful if anyone could explain that in detail.

推荐答案

注解种类之间的第一个主要区别是它们是在编译时使用然后丢弃(如 @Override)还是放置在已编译的类文件中并在运行时可用(如 Spring 的 @Component).这由 @Retention 决定注释的策略.如果您正在编写自己的注释,则需要确定该注释是在运行时(可能用于自动配置)还是仅在编译时(用于检查或代码生成)有用.

The first main distinction between kinds of annotation is whether they're used at compile time and then discarded (like @Override) or placed in the compiled class file and available at runtime (like Spring's @Component). This is determined by the @Retention policy of the annotation. If you're writing your own annotation, you'd need to decide whether the annotation is helpful at runtime (for autoconfiguration, perhaps) or only at compile time (for checking or code generation).

当编译带有注解的代码时,编译器会看到注解就像它看到源元素上的其他修饰符一样,比如访问修饰符 (public/private) 或 最后.当它遇到一个注解时,它会运行一个注解处理器,它就像一个插件类,表示它对特定的注解感兴趣.注释处理器通常使用反射 API 来检查正在编译的元素,并且可以简单地对它们运行检查、修改它们或生成要编译的新代码.@Override 是第一个例子;它使用反射 API 来确保它可以在超类之一中找到方法签名的匹配项,如果不能,则使用 Messager 导致编译错误.

When compiling code with annotations, the compiler sees the annotation just like it sees other modifiers on source elements, like access modifiers (public/private) or final. When it encounters an annotation, it runs an annotation processor, which is like a plug-in class that says it's interested a specific annotation. The annotation processor generally uses the Reflection API to inspect the elements being compiled and may simply run checks on them, modify them, or generate new code to be compiled. @Override is an example of the first; it uses the Reflection API to make sure it can find a match for the method signature in one of the superclasses and uses the Messager to cause a compile error if it can't.

有许多关于编写注释处理器的教程;这里有一个有用的.查看 Processor<上的方法/code> interface 用于编译器如何调用注释处理器;主要操作发生在 process 方法中,每次编译器看到具有匹配注释的元素时都会调用该方法.

There are a number of tutorials available on writing annotation processors; here's a useful one. Look through the methods on the Processor interface for how the compiler invokes an annotation processor; the main operation takes place in the process method, which gets called every time the compiler sees an element that has a matching annotation.

这篇关于像@Override 这样的注释在 Java 内部如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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