我发现了几个与此相关(不重复)的问题,但它们并不令我满意。
我不明白在哪里以及为什么要使用自定义注释
?
在书上看了一个自定义注解的例子,但是没有解释透彻。
@interface MyAnno
{
String str();
int val();
}
class MyClass
{
@MyAnno(str = "Annotation example", val = 100)
public static void myMeth()
{
System.out.println("Inside myMeth()");
}
}
class CustomAnno
{
public static void main(String args[])
{
MyClass.myMeth();
}
}
输出符合预期 Inside myMeth()
。
我对这个例子有几个问题。
1- How can I use
String str()
andint val()
in this program? ORWhat is the use of any abstract method of an
custom annotation
?2- Why
custom annotations
. I mean that what effect they are having on any code.3- How can I create an annotation which is having effects like @override is having?(I mean any kind of effect which can be noticed)
如果这个例子对你没用,那么请给我一个合适的小例子,其中使用了自定义注释
。
最佳答案
使用自定义注释的三个主要原因是:
- 减少编写代码的工作量(编译时注释处理器为您生成代码)。这是一个教程:part 1 , part 2 .
- 提供额外的正确性保证(编译时注释处理器会警告您错误)。一个很好的工具是 Checker Framework ,这可以防止空指针取消引用、并发错误等。
- 自定义行为(在运行时,您的代码使用反射检查注解,并根据注解是否存在做出不同的行为)。 Hibernate 等框架以这种方式使用注释;还可以看到 Oracle article .
与其他非注释方法相比,在每种情况下,使用注释都会降低代码中出错的可能性。
关于java - 使用自定义注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31103302/