简体   繁体   English

是否有任何方法可以强制使用某些特定的注释以及Java中的某些特定方法

[英]Is there any way to make it mandatory to use some specific annotation along with some particular method in Java

A class implementing interface ensures that all the methods in the interface are defined in the class, likewise, is there any way to tell the JVM that some specific annotations should be used in implementing class. 类实现接口确保接口中的所有方法都在类中定义,同样,有没有办法告诉JVM应该在实现类时使用某些特定的注释。 Consider the following interface 请考虑以下界面

public interface TestClass{
    @BeforeClass
    public void setup();
    @AfterClass
    public void tearDown();
}

and following is the implementing class 以下是实施类

public class TestScripts implements TestClass{
    @BeforeClass
    public void setup(){
        /*method body*/
    }
    @AfterClass
    public void tearDown(){
       /*method body*/
   }
}

All I want is that the compiler should show error if @BeforeClass annotation is not used with the method public void setup() and @AfterClass annotation is not used with the method public void tearDown() . 我想要的是,如果@BeforeClass注释未与方法public void setup()使用,并且@AfterClass注释不与方法public void tearDown()一起使用,编译器应该显示错误。 Any way to achieve this? 有没有办法实现这个目标?

You can't enforce this but what you can enforce is that a sub-class implements an abstract method. 您不能强制执行此操作,但您可以强制执行的是子类实现抽象方法。

public abstract class TestClass {
    @BeforeClass
    public void beforeClass(){
        setup();
    }

    protected void abstract setup();

    @AfterClass
    public void afterClass(){
       tearDown();
   }

    protected void abstract tearDown();
}

and then any sub-class has to implement these methods and they will be called based on the annotation. 然后任何子类都必须实现这些方法,它们将根据注释进行调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有一种方法可以使特定类的子类中的特定Java注释成为必需的 - Is there a way to make a specific Java annotation mandatory in subclasses of a specific class 通过在Java中提供我的自定义注释,可以在执行任何方法之前和之后执行一些代码 - execute some code before and after of any method execution only by giving my custom annotation in java 是否可以强制使用 Java 注释的值? - Is it possible to make a Java annotation's value mandatory? Java注释在方法之前和之后执行一些代码 - Java annotation to execute some code before and after method 如何只允许在 Java 中的方法参数中使用某些注释进行注释的类? - How to allow only classes annotated with some annotation in method parameters in Java? 如何使用jframe制作一些特定的宽度和高度以及一些自动-Java - how to make some specific widths and heights and some auto with jframes - Java 我想返回一些东西并执行其他方法。 JAVA有什么办法吗? - I want to return something and execute some other method. Is there any way in JAVA? Java:有没有办法让一个类(库的)只能由一个特定线程访问? - Java: Is there some way to make one class (of a library) be only accessible by one specific thread? 如何在特定程序包中带一些注释的类 - How take classes with some annotation in specific package 关于方法的Spring @Transactional注释的一些说明 - Some clarification about Spring @Transactional annotation on a method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM