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

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

问题描述

任何人都可以向我解释一下java中内部注释是如何工作的吗?

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

我知道如何通过在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 )或 final 。当遇到注释时,它会运行一个注释处理器,就像一个插件类,它说它对特定的注释很感兴趣。注释处理器通常使用Reflection API来检查正在编译的元素,并且可以简单地对它们运行检查,修改它们或生成要编译的新代码。 @Override 是第一个例子;它使用Reflection 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.

有很多关于编写注释处理器的教程; 这是一个有用的。查看 处理器接口,了解编译器如何调用注释处理器;主要操作发生在进程方法中,每次编译器看到具有匹配注释的元素时都会调用该方法。

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