java - 使用自定义注解

标签 java annotations

我发现了几个与此相关(不重复)的问题,但它们并不令我满意。

我不明白在哪里以及为什么要使用自定义注释

在书上看了一个自定义注解的例子,但是没有解释透彻。

@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() and int val() in this program? OR

What 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/

相关文章:

java - 名称 'File' 在库 'dart:html' 和 'dart:io' 中定义

java - 如何将逻辑与 Controller 分离并使用注释将其放入某些处理程序?

java - java注解的执行顺序

java - 我的工厂怎么了?

java - 项目树更改后的 Spring UnsatisfiedDependencyException

java - 为什么在使用java命令调用程序时没有使用java Xmx选项?

java - 使用orientdb注解自动填充Pojo

java - 确定 ArrayList 是否有序的通用方法 (Java)

java 编码风格 : one annotation with parameters, 还是只有一个注释的多个注释?

java - 为什么 Struts 2 注解没有 LongRangeFieldValidator