Home >Java >javaTutorial >A detailed introduction to Java custom annotations

A detailed introduction to Java custom annotations

黄舟
黄舟Original
2017-09-25 10:37:231133browse

This article mainly introduces the relevant information about the detailed explanation of examples of java custom annotations. Friends who need it can refer to

java The detailed explanation of examples of custom annotations

Java's Annotation was introduced after version 5.0 and can be used to create documentation, track dependencies in code, and perform compile-time checks. Annotations are for the virtual machine to see and represent some special functions of the program. The JDK provides three annotations: @Override, @SuppressWarning, and @Deprecated. There are also meta-annotations, @Target, @Retention, @Documented, and @Inherited. The role of the meta-annotation is to annotate other annotations.

If you want to understand annotations, you must understand custom annotations. Understanding is achieved through reflection.

First, let’s customize an annotation,


@Retention(value=RetentionPolicy.RUNTIME) 
public @interface MyTest { 
 
}

Then write a test demo


public class AnnotationDemo1 { 
  @MyTest 
  public void demo1(){ 
    System.out.println("方法1..."); 
  } 
   
  @MyTest 
  public void demo2(){ 
    System.out.println("方法2..."); 
  } 
  @Test 
  public void demo3(){ 
    System.out.println("方法3..."); 
  }

Finally, all methods with Mytest annotations in AnnotationDemo1 are run, followed by the running class


public class DemoRunner { 
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {  
    //获得测试类的class 
    Class clazz=AnnotationDemo1.class; 
    //获得class中的所有的方法 
    Method[] mothods=clazz.getMethods(); 
    //遍历每个方法, 
    for(Method method:mothods){ 
      boolean flag = method.isAnnotationPresent(MyTest.class); 
       System.out.println(flag); 
      if(flag){ 
        // 说明方法上有MyTest注解: 
        method.invoke(clazz.newInstance(), null); 
      } 
    } 
  } 
}

Finally The test can output method 1... and method 2..., which makes it easy to implement custom annotations.

The above is the detailed content of A detailed introduction to Java custom annotations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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