本文介绍了如果在接口中声明一个注解与一个方法相关联,我们是否可以强制在实现类中存在注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于 Java 中注解的使用.我在接口中声明它时将注释与方法相关联.在实现时,我如何确保注释与@Override 注释一起携带,如果没有,它应该抛出编译错误?

This is regarding use of annotations in Java. I associated an annotation with a method while declaring it in the interface. While implementing, how can I ensure that the annotation is carried along with @Override annotation and if not, it should throw a compilation error?

谢谢.

推荐答案

你不能.

您需要编写一些代码来执行此操作(在您的应用程序加载时间,或使用 apt)

You need to write some code to do this (either on your applciation load time, or using apt)

我有同样的场景,并创建了我自己的注释:

I had the same scenario, and created an annotation of my own:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface DependsOn {
    Class<? extends Annotation>[] value();

    /**
     * Specifies whether all dependencies are required (default),
     * or any one of them suffices
     */
    boolean all() default true;
}

并将其应用于其他注释,例如:

and applied it to other annotations, like:

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
@DependsOn(value={Override.class})
public @interface CustomAnnotation {
}

重要提示:请记住,@Override 具有编译时 (SOURCE) 保留策略,即它在运行时不可用.

Imporant: have in mind that @Override has a compile-time (SOURCE) retention policy, i.e. it isn't available at run-time.

这篇关于如果在接口中声明一个注解与一个方法相关联,我们是否可以强制在实现类中存在注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:38