JavaSE- Annotation

1- What is a comment

1.1 Basic concepts

Used in classes, methods, member variable methods, constructors, etc. to perform compiling constraints on components. Annotation is a new feature of JDK1.5.

Annotation is a kind of mark, it is a part of the class, and can carry some extra information to the class. The annotation is for the compiler or JVM, and the compiler or JVM can complete the corresponding function according to the annotation.

1.2 Annotation

  • It is not the program itself, but the program can be explained (marked). Method override constraints @Override
  • It can be read by other programs (such as compilers, etc.). Most of the most powerful framework technologies today are using annotations and reflections.

1.3 Annotation format

Annotations exist in the code as "@ annotation name", you can also add some parameter values, for example: @SuppressWarnings(value="unchecked")

Code example

public class AnnotationDemo01 {
    
    
    
}

@FunctionalInterface
interface Stu{
    
    
    void test();
}

2- Built-in annotations

@Override

Defined in java.lang.Override, this annotation only applies to rhetorical methods, which means that a method declaration intends to override another method declaration in the superclass.

@Deprecated

Defined in java.lang.Deprecated, this annotation can be used for rhetorical methods, attributes, and classes.
Means that programmers are not encouraged to use such an element, usually because it is dangerous or there are better options.

@SuppressWarnings

Defined in java.lang.SuppressWarnings,Used to suppress warning messages at compile time. Different from the previous two comments, you need to add a parameter to use it correctly. These parameters are already defined, just use them selectively.

2.1 Code example

package cn.annotation_01;

import java.util.ArrayList;
import java.util.List;

public class Annotation01 extends Object{
    
    
    // 1.重写的注解
    @Override
    public String toString() {
    
    
        return super.toString();
    }

    // 2.方法过时了,不建议使用,可能存在问题,并不是不能使用!
    @Deprecated
    public static void test01(){
    
    
        System.out.println("测试 @Deprecated");
    }

    //3. 发现 参数类型和参数名称,并不是方法!
   @SuppressWarnings("all")
    public void test02(){
    
    
        List list = new ArrayList<>();
   }

    public static void main(String[] args) {
    
    
        // 调用方法
        test01();
    }
}

3-element annotation

3.1 Basic concepts

Meta annotations are provided by Sun, and meta annotations are annotations used on custom annotations. Meta annotations are used to annotate custom annotations.

3.2 Meta-annotation types

@Target

Used to describe the scope of use of annotations (ie: where the described annotations can be used).

@Retention

Indicates at what level the annotation information needs to be saved, used to describe the life cycle of the annotation, (SOURCE <CLASS <RUNTIME)

@Document

Explain that the annotation will be included in the javadoc

@Inherited

Explain that the subclass can inherit the annotation in the parent class

3.3 Code example

package cn.annotation_01;

import java.lang.annotation.*;

public class Annotation02 {
    
    
    public void test(){
    
    

    }
}

// 1.定义一个注解
// Target 表示注解可以用到什么地方
@Target(value = {
    
    ElementType.METHOD, ElementType.TYPE})

// 2.Retention 注解在什么地方还有效
// runtime > class > sources
@Retention(value = RetentionPolicy.RUNTIME)

// 3.Deprecated 表示是否将注解生成在Javadoc中
@Deprecated

// 4.Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
    
    

}

4- custom annotation

4.1 Basic concepts

When using @interface custom annotations, it automatically inherits the java.lang.annotation.Annotation interface.

Custom annotation format

[修饰符] @interface 注解名{
    
    
         // 其中的每一个方法实际上是声明了一个配置参数。
}

Parameter Type

The name of the method is the name of the parameter, and the return value type is the type of the parameter(The return value can only be the basic type, Class, String, enum).
The default value of the parameter can be declared by default. If there is only one parameter member, the parameter name is generally value. The annotation element must have a value. When defining the annotation element, an empty string is often used, with 0 as the default value.

4.2 Code example

package cn.annotation_01;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*
* 自定义注解
*/
public class Test03 {
    
    
    // 注解可以显示赋值,如果没有默认值,就必须给注解赋值
    @MyAnnotation3(age = 26, name = "guardwhy")
    public void test01(){
    
    }

    @MyAnnotation4("guardwhy")
    public void test02(){
    
    
        
    }
}

// 定义注解
@Target({
    
    ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    
    
    // 注解的参数: 参数类型 + 参数名();
    String name() default "";
    int age();
    // 如果默认值为-1,代表不存在.
    int id() default -1;
    String[] schools() default {
    
    "计算机工程学院", "中山大学"};
}

@Target({
    
    ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation4{
    
    
    String value();
}

4.3 Reflective Reading Notes

Code example

package cn.annotation_02;

import java.lang.annotation.*;
import java.lang.reflect.Field;

/*
* 学生类
*/
@Tablestu("db_student")
class Student{
    
    
    // 成员属性
    @Fieldstu(columnName="db_id", type = "int", length = 10)
    private int id;
    @Fieldstu(columnName="db_age", type = "int", length = 10)
    private int age;
    @Fieldstu(columnName = "db_name", type = "varchar", length = 6)
    private String name;

    public Student() {
    
    

    }

    public Student(int id, String name, int age) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Tablestu{
    
    
    String value();
}

// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Fieldstu{
    
    
    String columnName();
    String type();
    int length();
}

public class Test01 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        // 1.获得Class类对象
        Class c1 = Class.forName("cn.annotation_02.Student");
        // 2.通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
    
    
            System.out.println(annotation); // @cn.annotation_02.Tablestu(value=db_student)
        }

        // 3.获得注解的value的值
        Tablestu tablestu = (Tablestu)c1.getAnnotation(Tablestu.class);
        String value = tablestu.value();
        System.out.println(value);  // db_student

        // 4.获得类指定的注解
        Field f = c1.getDeclaredField("id");
        Fieldstu annotation = f.getDeclaredAnnotation(Fieldstu.class);
        System.out.println(annotation.columnName());    // db_id
        System.out.println(annotation.type()); // int
        System.out.println(annotation.length()); // 10
    }
}

Guess you like

Origin blog.csdn.net/hxy1625309592/article/details/114444653