Home > Java > javaTutorial > body text

All the Java annotations you want are here, take a look.

php是最好的语言
Release: 2018-07-30 11:57:47
Original
1592 people have browsed it

Introduce a picture at the beginning of the article.

All the Java annotations you want are here, take a look.

Annotation in Chinese means annotation and annotation. Annotation is a very important knowledge point in Java, but it is often difficult for novices to understand.

I personally think that one of the main characteristics of poor technical documents is the use of professional terms to introduce professional terms.

For example:

Java annotations are used to provide metadata for Java code. As metadata, annotations do not directly affect the execution of your code, but there are some types of annotations that can actually be used for this purpose. Java annotations were added to Java starting with Java5.

This is the Java annotation on most websites. The explanation is indeed correct, but to be honest, when I first learned it, my mind was blank. What is this? It was as if he hadn't heard anything. Because the concept is too abstract, it is really difficult for beginners to understand it. Then as they continue to strengthen their practice during their own development, they will slowly form a correct understanding of it.

When I was writing this article, I was thinking. How can I or my readers understand the concept of annotation more intuitively? Do you want to translate the instructions in official documents? I immediately rejected this answer.

Later, I thought of something - ink. Ink can evaporate and have different colors, which is perfect for explaining and annotating.

However, after I continued to think divergently, I thought of something that could better replace ink, and that was a seal. The seal can be dipped in different inks or ink pads, and the text or pattern of the seal can be customized. If you like, it can also be stamped on any surface you want to stamp.

However, after I continued to think divergently, I thought of something that could better replace the seal, and that was a label. The label is a piece of convenient paper, and the content on the label can be freely defined. Common examples include product price tags on shelves, book coding tags in libraries, name category tags of chemical materials in laboratories, etc.

And, speaking more abstractly, a label is not necessarily a piece of paper, it can be an attribute evaluation of people and things. In other words, labels have explanations for abstract things.

All the Java annotations you want are here, take a look.

So, based on this, I completed my knowledge upgrade, and I decided to use labels to explain annotations.

Annotations are like tags

Back to the beginning of the blog post, a comment on a news client had the habit of building buildings, so "Jobs redefined mobile phones, Luo Yonghao redefined stupid X" It often appears on the comment floor very neatly, and the majority of netizens have been enjoying this behavior for a long time. This is actually equivalent to labeling.

In the eyes of some netizens, Luo Yonghao has become synonymous with stupidity.

The majority of netizens have labeled Luo Yonghao "Stupid Labels like

On the other side of the Internet, Lao Luo has naturally gained a large number of loyal fans with his charisma, and they have put another label on Lao Luo.
All the Java annotations you want are here, take a look.

Lao Luo is still Lao Luo, but because people put different labels on him, they have very different views on him. People who don’t like him comment and criticize and ridicule him on the Internet all day long. , and people who admire and admire him will be willing to earn money to buy tickets for the launch of Smartisan mobile phones.

I do not intend to evaluate these two behaviors. Let me give another example.

"Qi Pa Shuo" is a very popular debate program on the Internet in recent years. In it, debater Chen Ming was attacked by another debater Ma Weiwei, saying that he was "standing in the center of the universe and calling for love", and then posted He got a big label - "Chicken Soup Man". From then on, when the audience saw Chen Ming again, the first thing that came to mind was "Chicken Soup Man". In fact, Chen Ming himself is very good. , he is a role model, has a decent style, and speaks and behaves well. However, in the Internet, due to the entertainment-oriented environment, people are more willing to perceive everything with an entertainment mentality, so the "Chicken Soup Man" became as Chen Ming himself said. A label that cannot be removed.

We can make an abstract summary. Labels are evaluations and explanations of certain aspects of the behavior of things.

At this point, we can finally introduce the main character of this article.

Beginners can understand annotations this way: imagine that the code is alive, and annotations are labels attached to some living individuals in the code. To simplify, an annotation is like a label.

Before learning any specific syntax of annotations, you can think of an annotation as a label. This helps you quickly understand its general function. If a beginner has his brain empty during the learning process, please don’t panic and say to yourself:

annotations, labels. Annotation, label.

Annotation syntax

Because it is rare in normal development, I believe many people will think that the status of annotations is not high. In fact, like classes and interfaces, annotations also belong to a type. It is a concept introduced in Java SE 5.0 version.

Definition of annotations

Annotations are defined through the @interface keyword.

public @interface TestAnnotation {}
Copy after login
  • 1

  • 2

Its form is very similar to the interface, but there are more in front an @ symbol. The above code creates an annotation named TestAnnotaion.

You can simply understand that a label named TestAnnotation is created.

Application of annotations

An annotation is created above, so what is the method of using the annotation.

@TestAnnotationpublic class Test {}
Copy after login
  • 1

  • 2

  • 3

Create a class Test, and then add @TestAnnotation where the class is defined to annotate the class with TestAnnotation.

You can simply understand it as attaching the TestAnnotation label to the Test class.

However, if you want annotations to work properly, you need to introduce a new concept, which is meta-annotations.

Meta-annotation

What does meta-annotation mean?

Meta-annotations are annotations that can be annotated on annotations, or meta-annotations are a basic annotation, but they can be applied to other annotations.

If it is difficult to understand, you can understand it like this. Meta-annotation is also a tag, but it is a special tag. Its function and purpose is to explain other ordinary tags.

There are 5 types of meta tags: @Retention, @Documented, @Target, @Inherited, and @Repeatable.

@Retention

Retention means retention period in English. When @Retention is applied to an annotation, it explains the lifetime of the annotation.

Its value is as follows:
- RetentionPolicy.SOURCE annotation is only retained in the source code stage, and will be discarded and ignored when the compiler compiles.
- The RetentionPolicy.CLASS annotation is only retained until compilation is in progress, it will not be loaded into the JVM.
- RetentionPolicy.RUNTIME annotations can be retained until the program is running, and they will be loaded into the JVM, so they can be obtained when the program is running.

We can deepen our understanding in this way. When @Retention explains a label, it specifies the time when the label is posted. @Retention is equivalent to stamping a timestamp on a label, and the timestamp indicates the time period during which the label was posted.

@Retention(RetentionPolicy.RUNTIME)public @interface TestAnnotation {}
Copy after login
  • 1

  • 2

  • 3

In the above code, we specify that TestAnnotation can be obtained during the program running cycle, so its life cycle is very long.

@Documented

As the name suggests, this meta-annotation must be related to the document. Its function is to include elements in annotations into Javadoc.

@Target

Target means target, and @Target specifies the place where the annotation is used.

You can understand it this way, when an annotation is annotated with @Target, the annotation is limited to the application scenario.

By analogy to tags, originally tags can be posted wherever you want, but because of the existence of @Target, the place where they are posted is very specific, for example, they can only be posted to methods and classes. , method parameters, etc. @Target has the following values

  • ElementType.ANNOTATION_TYPE can annotate an annotation

  • ElementType.CONSTRUCTOR can annotate the constructor

  • ElementType.FIELD can annotate properties

  • ElementType.LOCAL_VARIABLE can annotate local variables

  • ElementType.METHOD can annotate a method

  • ElementType.PACKAGE can annotate a package

  • ElementType.PARAMETER can annotate a method Annotate the parameters inside

  • ElementType.TYPE You can annotate a type, such as a class, interface, or enumeration

@Inherited

Inherited means inheritance, but it does not mean that the annotation itself can be inherited. It means that if a super class is annotated with an @Inherited annotation, then if its subclass is not applied by any annotation , then this subclass inherits the annotations of the superclass.
is rather abstract. code to explain.

@Inherited@Retention(RetentionPolicy.RUNTIME)@interface Test {}@Testpublic class A {}public class B extends A {}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • ##5

  • 6

  • 7

  • 8

  • 9

  • ##10
  • 11

注解 Test 被 @Inherited 修饰,之后类 A 被 Test 注解,类 B 继承 A,类 B 也拥有 Test 这个注解。

可以这样理解:

老子非常有钱,所以人们给他贴了一张标签叫做富豪。

老子的儿子长大后,只要没有和老子断绝父子关系,虽然别人没有给他贴标签,但是他自然也是富豪。

老子的孙子长大了,自然也是富豪。

这就是人们口中戏称的富一代,富二代,富三代。虽然叫法不同,好像好多个标签,但其实事情的本质也就是他们有一张共同的标签,也就是老子身上的那张富豪的标签。

@Repeatable

Repeatable 自然是可重复的意思。@Repeatable 是 Java 1.8 才加进来的,所以算是一个新的特性。

什么样的注解会多次应用呢?通常是注解的值可以同时取多个。

举个例子,一个人他既是程序员又是产品经理,同时他还是个画家。

@interface Persons {
    Person[]  value();
}@Repeatable(Persons.class)@interface Person{
    String role default "";
}@Person(role="artist")@Person(role="coder")@Person(role="PM")public class SuperMan{}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

注意上面的代码,@Repeatable 注解了 Person。而 @Repeatable 后面括号中的类相当于一个容器注解。

什么是容器注解呢?就是用来存放其它注解的地方。它本身也是一个注解。

我们再看看代码中的相关容器注解。

@interface Persons {
    Person[]  value();
}
Copy after login
  • 1

  • 2

  • 3

按照规定,它里面必须要有一个 value 的属性,属性类型是一个被 @Repeatable 注解过的注解数组,注意它是数组。

如果不好理解的话,可以这样理解。Persons 是一张总的标签,上面贴满了 Person 这种同类型但内容不一样的标签。把 Persons 给一个 SuperMan 贴上,相当于同时给他贴了程序员、产品经理、画家的标签。

我们可能对于 @Person(role=”PM”) 括号里面的内容感兴趣,它其实就是给 Person 这个注解的 role 属性赋值为 PM ,大家不明白正常,马上就讲到注解的属性这一块。

注解的属性

注解的属性也叫做成员变量。注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明,其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface TestAnnotation {

    int id();

    String msg();

}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

上面代码定义了 TestAnnotation 这个注解中拥有 id 和 msg 两个属性。在使用的时候,我们应该给它们进行赋值。

赋值的方式是在注解的括号内以 value=”” 形式,多个属性之前用 ,隔开。

@TestAnnotation(id=3,msg="hello annotation")public class Test {}
Copy after login
  • 1

  • 2

  • 3

  • 4

需要注意的是,在注解中定义属性时它的类型必须是 8 种基本数据类型外加 类、接口、注解及它们的数组。

注解中属性可以有默认值,默认值需要用 default 关键值指定。比如:

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface TestAnnotation {

    public int id() default -1;    public String msg() default "Hi";

}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

TestAnnotation 中 id 属性默认值为 -1,msg 属性默认值为 Hi。
它可以这样应用。

@TestAnnotation()public class Test {}
Copy after login
  • 1

  • 2

因为有默认值,所以无需要再在 @TestAnnotation 后面的括号里面进行赋值了,这一步可以省略。

另外,还有一种情况。如果一个注解内仅仅只有一个名字为 value 的属性时,应用这个注解时可以直接接属性值填写到括号内。

public @interface Check {
    String value();
}
Copy after login
  • 1

  • 2

  • 3

上面代码中,Check 这个注解只有 value 这个属性。所以可以这样应用。

@Check("hi")int a;
Copy after login
  • 1

  • 2

这和下面的效果是一样的

@Check(value="hi")int a;
Copy after login
  • 1

  • 2

最后,还需要注意的一种情况是一个注解没有任何属性。比如

public @interface Perform {}
Copy after login
  • 1

  • 2

那么在应用这个注解的时候,括号都可以省略。

@Performpublic void testMethod(){}
Copy after login
  • 1

  • 2

Java 预置的注解

学习了上面相关的知识,我们已经可以自己定义一个注解了。其实 Java 语言本身已经提供了几个现成的注解。

@Deprecated

这个元素是用来标记过时的元素,想必大家在日常开发中经常碰到。编译器在编译阶段遇到这个注解时会发出提醒警告,告诉开发者正在调用一个过时的元素比如过时的方法、过时的类、过时的成员变量。

public class Hero {

    @Deprecated
    public void say(){
        System.out.println("Noting has to say!");
    }    public void speak(){
        System.out.println("I have a dream!");
    }


}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

定义了一个 Hero 类,它有两个方法 say() 和 speak() ,其中 say() 被 @Deprecated 注解。然后我们在 IDE 中分别调用它们。
All the Java annotations you want are here, take a look.

可以看到,say() 方法上面被一条直线划了一条,这其实就是编译器识别后的提醒效果。

@Override

这个大家应该很熟悉了,提示子类要复写父类中被 @Override 修饰的方法

@SuppressWarnings

阻止警告的意思。之前说过调用被 @Deprecated 注解的方法后,编译器会警告提醒,而有时候开发者会忽略这种警告,他们可以在调用的地方通过 @SuppressWarnings 达到目的。

@SuppressWarnings("deprecation")public void test1(){
    Hero hero = new Hero();
    hero.say();
    hero.speak();
}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

@SafeVarargs

参数安全类型注解。它的目的是提醒开发者不要用参数做一些不安全的操作,它的存在会阻止编译器产生 unchecked 这样的警告。它是在 Java 1.7 的版本中加入的。

@SafeVarargs // Not actually safe!
    static void m(List<String>... stringLists) {
    Object[] array = stringLists;
    List<Integer> tmpList = Arrays.asList(42);
    array[0] = tmpList; // Semantically invalid, but compiles without warnings
    String s = stringLists[0].get(0); // Oh no, ClassCastException at runtime!}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

上面的代码中,编译阶段不会报错,但是运行时会抛出 ClassCastException 这个异常,所以它虽然告诉开发者要妥善处理,但是开发者自己还是搞砸了。

Java 官方文档说,未来的版本会授权编译器对这种不安全的操作产生错误警告。

@FunctionalInterface

函数式接口注解,这个是 Java 1.8 版本引入的新特性。函数式编程很火,所以 Java 8 也及时添加了这个特性。

函数式接口 (Functional Interface) 就是一个具有一个方法的普通接口。

比如

@FunctionalInterfacepublic interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object&#39;s
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

我们进行线程开发中常用的 Runnable 就是一个典型的函数式接口,上面源码可以看到它就被 @FunctionalInterface 注解。

可能有人会疑惑,函数式接口标记有什么用,这个原因是函数式接口可以很容易转换为 Lambda 表达式。这是另外的主题了,有兴趣的同学请自己搜索相关知识点学习。

注解的提取

博文前面的部分讲了注解的基本语法,现在是时候检测我们所学的内容了。

我通过用标签来比作注解,前面的内容是讲怎么写注解,然后贴到哪个地方去,而现在我们要做的工作就是检阅这些标签内容。 形象的比喻就是你把这些注解标签在合适的时候撕下来,然后检阅上面的内容信息。

要想正确检阅注解,离不开一个手段,那就是反射。

注解与反射。

注解通过反射获取。首先可以通过 Class 对象的 isAnnotationPresent() 方法判断它是否应用了某个注解

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}
Copy after login
  • 1

  • 2

然后通过 getAnnotation() 方法来获取 Annotation 对象。

 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}
Copy after login
  • 1

  • 2

或者是 getAnnotations() 方法。

public Annotation[] getAnnotations() {}
Copy after login
  • 1

  • 2

前一种方法返回指定类型的注解,后一种方法返回注解到这个元素上的所有注解。

如果获取到的 Annotation 如果不为 null,则就可以调用它们的属性方法了。比如

@TestAnnotation()public class Test {

    public static void main(String[] args) {        boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);        if ( hasAnnotation ) {
            TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);

            System.out.println("id:"+testAnnotation.id());
            System.out.println("msg:"+testAnnotation.msg());
        }

    }

}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

程序的运行结果是:

id:-1msg:
Copy after login
  • 1

  • 2

  • 3

这个正是 TestAnnotation 中 id 和 msg 的默认值。

上面的例子中,只是检阅出了注解在类上的注解,其实属性、方法上的注解照样是可以的。同样还是要假手于反射。

@TestAnnotation(msg="hello")public class Test {

    @Check(value="hi")    int a;    @Perform
    public void testMethod(){}    @SuppressWarnings("deprecation")    public void test1(){
        Hero hero = new Hero();
        hero.say();
        hero.speak();
    }    public static void main(String[] args) {        boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);        if ( hasAnnotation ) {
            TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);            //获取类的注解
            System.out.println("id:"+testAnnotation.id());
            System.out.println("msg:"+testAnnotation.msg());
        }        try {
            Field a = Test.class.getDeclaredField("a");
            a.setAccessible(true);            //获取一个成员变量上的注解
            Check check = a.getAnnotation(Check.class);            if ( check != null ) {
                System.out.println("check value:"+check.value());
            }

            Method testMethod = Test.class.getDeclaredMethod("testMethod");            if ( testMethod != null ) {                // 获取方法中的注解
                Annotation[] ans = testMethod.getAnnotations();                for( int i = 0;i < ans.length;i++) {
                    System.out.println("method testMethod annotation:"+ans[i].annotationType().getSimpleName());
                }
            }
        } catch (NoSuchFieldException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (SecurityException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (NoSuchMethodException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println(e.getMessage());
        }



    }

}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

  • 21

  • 22

  • 23

  • 24

  • 25

  • 26

  • 27

  • 28

  • 29

  • 30

  • 31

  • 32

  • 33

  • 34

  • 35

  • 36

  • 37

  • 38

  • 39

  • 40

  • 41

  • 42

  • 43

  • 44

  • 45

  • 46

  • 47

  • 48

  • 49

  • 50

  • 51

  • 52

  • 53

  • 54

  • 55

  • 56

  • 57

  • 58

  • 59

  • 60

  • 61

  • 62

  • 63

  • 64

  • 65

  • 66

  • 67

  • 68

  • 69

  • 70

它们的结果如下:

id:-1msg:hello
check value:himethod testMethod annotation:Perform
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

需要注意的是,如果一个注解要在运行时被成功提取,那么 @Retention(RetentionPolicy.RUNTIME) 是必须的。

注解的使用场景

我相信博文讲到这里大家都很熟悉了注解,但是有不少同学肯定会问,注解到底有什么用呢?

对啊注解到底有什么用?

我们不妨将目光放到 Java 官方文档上来。

文章开始的时候,我用标签来类比注解。但标签比喻只是我的手段,而不是目的。为的是让大家在初次学习注解时能够不被那些抽象的新概念搞懵。既然现在,我们已经对注解有所了解,我们不妨再仔细阅读官方最严谨的文档。

注解是一系列元数据,它提供数据用来解释程序代码,但是注解并非是所解释的代码本身的一部分。注解对于代码的运行效果没有直接影响。

注解有许多用处,主要如下:
- 提供信息给编译器: 编译器可以利用注解来探测错误和警告信息
- 编译阶段时的处理: 软件工具可以用来利用注解信息来生成代码、Html文档或者做其它相应处理。
- 运行时的处理: 某些注解可以在程序运行的时候接受代码的提取

值得注意的是,注解不是代码本身的一部分。

如果难于理解,可以这样看。罗永浩还是罗永浩,不会因为某些人对于他“傻x”的评价而改变,标签只是某些人对于其他事物的评价,但是标签不会改变事物本身,标签只是特定人群的手段。所以,注解同样无法改变代码本身,注解只是某些工具的的工具。

还是回到官方文档的解释上,注解主要针对的是编译器和其它工具软件(SoftWare tool)。

当开发者使用了Annotation 修饰了类、方法、Field 等成员之后,这些 Annotation 不会自己生效,必须由开发者提供相应的代码来提取并处理 Annotation 信息。这些处理提取和处理 Annotation 的代码统称为 APT(Annotation Processing Tool)。

现在,我们可以给自己答案了,注解有什么用?给谁用?给 编译器或者 APT 用的。

如果,你还是没有搞清楚的话,我亲自写一个好了。

亲手自定义注解完成某个目的

我要写一个测试框架,测试程序员的代码有无明显的异常。

—— 程序员 A : 我写了一个类,它的名字叫做 NoBug,因为它所有的方法都没有错误。
—— 我:自信是好事,不过为了防止意外,让我测试一下如何?
—— 程序员 A: 怎么测试?
—— 我:把你写的代码的方法都加上 @Jiecha 这个注解就好了。
—— 程序员 A: 好的。

NoBug.java

package ceshi;import ceshi.Jiecha;public class NoBug {

    @Jiecha
    public void suanShu(){
        System.out.println("1234567890");
    }    @Jiecha
    public void jiafa(){
        System.out.println("1+1="+1+1);
    }    @Jiecha
    public void jiefa(){
        System.out.println("1-1="+(1-1));
    }    @Jiecha
    public void chengfa(){
        System.out.println("3 x 5="+ 3*5);
    }    @Jiecha
    public void chufa(){
        System.out.println("6 / 0="+ 6 / 0);
    }    public void ziwojieshao(){
        System.out.println("我写的程序没有 bug!");
    }

}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

  • 21

  • 22

  • 23

  • 24

  • 25

  • 26

  • 27

  • 28

  • 29

  • 30

  • 31

  • 32

上面的代码,有些方法上面运用了 @Jiecha 注解。

这个注解是我写的测试软件框架中定义的注解。

package ceshi;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)public @interface Jiecha {}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

然后,我再编写一个测试类 TestTool 就可以测试 NoBug 相应的方法了。

package ceshi;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class TestTool {

    public static void main(String[] args) {        // TODO Auto-generated method stub

        NoBug testobj = new NoBug();

        Class clazz = testobj.getClass();

        Method[] method = clazz.getDeclaredMethods();        //用来记录测试产生的 log 信息
        StringBuilder log = new StringBuilder();        // 记录异常的次数
        int errornum = 0;        for ( Method m: method ) {            // 只有被 @Jiecha 标注过的方法才进行测试
            if ( m.isAnnotationPresent( Jiecha.class )) {                try {
                    m.setAccessible(true);
                    m.invoke(testobj, null);

                } catch (Exception e) {                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                    errornum++;
                    log.append(m.getName());
                    log.append(" ");
                    log.append("has error:");
                    log.append("\n\r  caused by ");                    //记录测试过程中,发生的异常的名称
                    log.append(e.getCause().getClass().getSimpleName());
                    log.append("\n\r");                    //记录测试过程中,发生的异常的具体信息
                    log.append(e.getCause().getMessage());
                    log.append("\n\r");
                } 
            }
        }


        log.append(clazz.getSimpleName());
        log.append(" has  ");
        log.append(errornum);
        log.append(" error.");        // 生成测试报告
        System.out.println(log.toString());

    }

}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

  • 21

  • 22

  • 23

  • 24

  • 25

  • 26

  • 27

  • 28

  • 29

  • 30

  • 31

  • 32

  • 33

  • 34

  • 35

  • 36

  • 37

  • 38

  • 39

  • 40

  • 41

  • 42

  • 43

  • 44

  • 45

  • 46

  • 47

  • 48

  • 49

  • 50

  • 51

  • 52

  • 53

  • 54

  • 55

  • 56

  • 57

  • 58

  • 59

  • 60

测试的结果是:

12345678901+1=111-1=03 x 5=15chufa has error:

  caused by ArithmeticException

/ by zero

NoBug has  1 error.
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

提示 NoBug 类中的 chufa() 这个方法有异常,这个异常名称叫做 ArithmeticException,原因是运算过程中进行了除 0 的操作。

所以,NoBug 这个类有 Bug。

这样,通过注解我完成了我自己的目的,那就是对别人的代码进行测试。

所以,再问我注解什么时候用?我只能告诉你,这取决于你想利用它干什么用。

注解应用实例

注解运用的地方太多了,因为我是 Android 开发者,所以我接触到的具体例子有下:

JUnit

JUnit 这个是一个测试框架,典型使用方法如下:

public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

@Test 标记了要进行测试的方法 addition_isCorrect().

ButterKnife

ButterKnife 是 Android 开发中大名鼎鼎的 IOC 框架,它减少了大量重复的代码。

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.tv_test)
    TextView mTv;    @Override
    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
    }
}
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

Dagger2

也是一个很有名的依赖注入框架。

Retrofit

很牛逼的 Http 网络访问框架

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);
Copy after login
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

当然,还有许多注解应用的地方,这里不一一列举。

总结

  1. 如果注解难于理解,你就把它类同于标签,标签为了解释事物,注解为了解释代码。

  2. 注解的基本语法,创建如同接口,但是多了个 @ 符号。

  3. 注解的元注解。

  4. 注解的属性。

  5. 注解主要给编译器及工具类型的软件用的。

  6. 注解的提取需要借助于 Java 的反射技术,反射比较慢,所以注解使用时也需要谨慎计较时间成本。

相关文章:

Java自定义注解

Java annotation tutorials and custom annotations

Related videos:

Comprehensive analysis of Java annotations

The above is the detailed content of All the Java annotations you want are here, take a look.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template