Java-----注解

1.什么是注解?

Annotation是JDK5.0开始引入的新技术。

Annotation的作用:

  1. 不是程序本身,可以对程序作出解释。(这一点,跟注释没什么区别)
  2. 可以被其他程序(比如:编译器)读取。(注解信息处理流程,是注解和注释的重大区别)

Annotation的格式:

--注解是以“@注释名”在代码中存在的,还可以添加一些参数值,例如:@SupperssWarnings(value="unchecked")。

Annotation在哪里使用?

--可以附加在package,class,method,field等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程实现对这些 元数据的访问。

2.内置注解

@Override ----(重写)

  定义在java.lang.Override中,此注释只适用于修辞方法,表示一个方法声明打算重写父类中的另一个方法声明。

package java.lang;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

@Deprecated ----(不推荐使用,带有一个中划线)

  定义在java.lang.Deprecated中,此注释可用于修辞方法、属性、类,表示不鼓励程序员使用这样的元素,通常是因为它很危险或存在更好的选择。

package java.lang;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}

@SuppressWarnings ----(抑制警告)

  定义在java.lang.SuppressWarnings中,用来抑制编译时的警告信息。

package java.lang;

import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    String[] value();
}

 3.自定义注解

关键字@interface

  元注解的作用就是负责注解其他注解。Java定义了4个标准的meta-annotation类型,它们被用来提供对其它annotation类型作说明。

  这些类型和它们所支持的类在java.lang.annotation包中可以找到

----@Target

----@Retention

----@Documented

----@Inherited

1.@Target的源码及作用范围

ElementType类型是一个枚举类型,里面都是固定的值

package java.lang.annotation;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {

   //参数类型           参数名
    ElementType[] value();
}

ElementType:

package java.lang.annotation;

//枚举
public enum ElementType {
    TYPE,

    FIELD,
    
    METHOD,

    PARAMETER,

    CONSTRUCTOR,

    LOCAL_VARIABLE,

    ANNOTATION_TYPE,

    PACKAGE,

  /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

其作用是给自定义的注解,描述它能加到什么地方。

2.@Retention的源码及作用范围

 注解保留策略(RetentionPolicy)

package java.lang.annotation;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {

    //也是一个枚举类型    参数名
    RetentionPolicy value();
}

RetentionPolicy:

package java.lang.annotation;

//枚举
public enum RetentionPolicy {
    SOURCE,
    
    CLASS,

    RUNTIME
}

 示例:

 自定义的注解:

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

//这就表示自定义注解只能用在方法上和类上
@Target(value = {ElementType.METHOD,ElementType.TYPE})//可以写到数组中
@Retention(value = RetentionPolicy.RUNTIME)//表示注解在运行时有效,可被反射(运行时)读取到
public @interface MyAnnotation {

    //写内容
    //           参数类型    参数名    默认值
    public String name() default "";//加了默认值 ""
    public int age() default 0;
    //表示不存在
    int id() default -1;//int indexOf("abc") 返回子字符在字符串中第一次出现的索引,如果没有的话,返回-1,也就是表示不存在
    
    String[] schools() default {"清华大学","北京大学"};
}
package com.xjs.annotation;

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


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

使用:

import com.xjs.annotation.XJSAnnotation;

public class Demo2 {
    
    @MyAnnotation(age=18,name="金泰妍")
    public void test() {
        
    }
    
    @XJSAnnotation("taeyeon")
    public void test2() {
        
    }
}


 例子:

1.注解的解析完全依赖于反射。

2.不要滥用注解,平常我们编程过程很少接触和使用注解,只有做设计,且不想让设计有过多的配置时。

Student.java:

package com.xjs.annotation;

//使用注解,使这个类和表对应
@XJSTable(value = "tb_student")
public class Student {
    
    @XJSField(columnName = "id", length = 10, type = "int")
    private int id;
    @XJSField(columnName = "sname", length = 10, type = "varcher")
    private String name;
    @XJSField(columnName = "age", length = 3, type = "int")
    private int age;
    
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public Student(int id, String name, int age) {
        super();
        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 + "]";
    }
    
}

自定义注解XJSTable.java:

package com.xjs.annotation;

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

@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
//自定义注解
public @interface XJSTable {
    String value();
}

自定义注解XJSField.java:

package com.xjs.annotation;

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

@Target(value = {ElementType.FIELD})//加在属性上
@Retention(value = RetentionPolicy.RUNTIME)
public @interface XJSField {
    String columnName();//列名
    String type();//类型
    int length();//长度
    
}

利用反射机制解析该类上加的注解Demo3.java:

package com.xjs.annotation;

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

/**
 * 使用反射读取注解的信息,模拟处理注解信息的流程
 * @author hp
 *
 */
public class Demo3 {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.xjs.annotation.Student");
            Annotation[] annotations = clazz.getDeclaredAnnotations();//获得这个类的所有注解
            for (Annotation annotation : annotations) {
                System.out.println(annotation);
            }
            
            //获得类指定的注解
            XJSTable xt= (XJSTable) clazz.getDeclaredAnnotation(XJSTable.class);
            System.out.println(xt.value());//获取这个类上的注解的value值
            
            //获得类的属性的注解
            Field f = clazz.getDeclaredField("name");
            XJSField xjsFile = f.getAnnotation(XJSField.class);
            System.out.println(xjsFile.length());
            
            //根据获得的表名,字段的信息,拼出SQL语句,然后,使用JDBC执行这个SQL,在数据库中生成相关的表的记录
            /*
             * 注解--->依赖反射,然后获取信息
               * 对象的每一个属性信息---JDBC--->通过SQL语句添加到数据库中对应的字段
             * 
             */
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/xjs1874704478/p/11185392.html