如何实现类似于@Override java 注释的东西? [英] How to implement something similar to the @Override java annotation?
问题描述
使用../java/lang/Override.java
中的jdk代码,
package java.lang;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
只需要注解声明,java编译器就足够智能以检测错误(编译时):
having just annotation declaration, java compiler is intelligent enough to detect error(compile time):
Example 类型的 toString123() 方法必须覆盖或实现超类型方法
在下面的问题代码中.
package annotationtype;
public class Example {
@Override public String toString() {
return "Override the toString() of the superclass";
}
@Override public String toString123() {
return "Override the toString123() of the superclass";
}
public static void main(String[] args) {
}
}
Override
的注解声明刚刚被编译为,
Annotation declaration for Override
just gets compiled to,
interface java.lang.Override extends java.lang.annotation.Annotation{
}
这只不过是一个接口
.
所以,
interface java.lang.Override
语法如何帮助java编译器在编译时检测上述错误?
How does interface java.lang.Override
syntax help java compiler to detect above error at compile time?
推荐答案
触发编译错误的实现不在于注解,而在于Java编译器.
The implementation that triggers the compile error doesn't lie in the annotation, it lies in the Java compiler.
如果你想自己写一个类似的注解处理器,你可以使用注解处理器API:http://docs.oracle.com/javase/7/docs/api/javax/annotation/processing/Processor.html
If you want to write your own similar annotation processor, you would use the annotation processor API: http://docs.oracle.com/javase/7/docs/api/javax/annotation/processing/Processor.html
这篇关于如何实现类似于@Override java 注释的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!