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

问题描述

这是关于利用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?

感谢。

推荐答案

您不能。

您需要写一些code要做到这一点(无论是在您的applciation加载时间,或使用的)

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 {
}

项重要的:有记住 @覆盖有一个编译时(来源)的保留策略,即它不可用在运行时。

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

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

10-26 22:38