注解

1、注解的概念和作用

注解就是符合一定格式的语法@xxx形式

注解的主要作用在于代替配置文件。使用注解可以提高开发效率,降低成本。

2、常见的注解

  • @Override:告知编译器方法重载
  • @Deprecated:标注过时
  • @SuppressWarnings:压制警告

3、元注解

  • @Target:代表注解修饰的范围,FIELD表示字段上使用,METHOD方法上使用,TYPE类上使用
  • @Retention:SOURCE表示注解在源码级别可见,CLASS表示注解在源码和字节码文件可见,RUNTIME表示注解在整个运行阶段都可见

自定义注解

 1 package com.alphajuns.case1;
 2 
 3 import java.lang.annotation.ElementType;
 4 import java.lang.annotation.Retention;
 5 import java.lang.annotation.RetentionPolicy;
 6 import java.lang.annotation.Target;
 7 
 8 @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
 9 @Retention(RetentionPolicy.RUNTIME)
10 public @interface MyTest {
11     
12 }

使用注解类

 1 package com.alphajuns.case1;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.junit.Test;
 7 
 8 public class TestDemo {
 9 
10     @SuppressWarnings({"rawtypes", "unused"})
11     public void method() {
12         List list = new ArrayList();
13         System.out.println("Method...");
14     }
15     
16     public void method0() {
17         @SuppressWarnings("all")
18         List list = new ArrayList();
19         System.out.println("Method...");
20     }
21     
22     @Test
23     public void method1() {
24         System.out.println("Method1...");
25     }
26 
27     @MyTest
28     public void method2() {
29         int i = 100;
30         System.out.println("Method2...");
31     }
32 
33     @MyTest
34     public void method3() {
35         System.out.println("Method3...");
36     }
37 
38 }

运行测试自定义注解

 1 package com.alphajuns.case1;
 2 
 3 import java.lang.reflect.InvocationTargetException;
 4 import java.lang.reflect.Method;
 5 
 6 public class MyTestParse {
 7 
 8     public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
 9         // 获得TestDemo的字节码文件
10         Class clazz = TestDemo.class;
11         // 获得所有方法
12         Method[] methods = clazz.getMethods();
13         if (methods != null) {
14             for (Method method : methods) {
15                 // 获得所有使用了@MyTest注解的方法
16                 boolean annotationPresent = method.isAnnotationPresent(MyTest.class);
17                 // 执行使用了@MyTest注解的方法
18                 if (annotationPresent) {
19                     method.invoke(clazz.newInstance(), null);
20                 }
21             }
22         }
23     }
24 
25 }
原文地址:https://www.cnblogs.com/alphajuns/p/9975410.html