[英]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.