12.java注解(Annotation)

注解(Annotation)

作用
    1.不是程序本身,可以对程序作出解释(这一点,跟注释没什么区别)
    2.可以被其他程序(如编译器等)读取。(注解信息处理流程,是注解与注释的重大区别。如果没有注解信息处理流程,则注解毫无意义)

格式
    @注释名  还可以添加一些参数值,例如@SuppressWarnings(value="unchecked")

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

常见内置注解

@Override    表示一个方法声明打算重写超类中的另一个方法的声明
@Deprecated  表示不鼓励使用这样的元素,通常是因为它很危险或存在更好的选择、
@SuppressWarnings  用来抑制编译时的警告信息和前两个注释不同,需要添加一个参数才能正确使用
 例如: @SuppressWarnings("unchecked")   @SuppressWarnings(value={"unchecked","deprecation"})常见参数如下:

参数含义
deprecation使用了过时的类或方法警告
unchecked执行了未检查的转换时的警告,如使用集合未指定泛型
fallthrough在switch语句使用时发生case穿透
path在类路径、源文件路径等中有不存在路径的警告
serial当在可序列话的类上缺少serialVersionUID定义时
finally任何finally子句不能完成时的警告
all以上所有情况的警告

自定义注解:

在自定义注解前先了解一下元注解


元注解的作用是负责注解其他注解。java中提供了4个标准的meta-annotation类型,它们被用来提供对其他annotation类型说明
这些类型和它们所支持的类可以在java.lang.annotation包中找到

@Target     @Retention     @Documented    @Inherited

@Target   作用:描述注解的使用范围(即被描述的注解可以用在什么地方)  例如:@Target(value=ElementType.TYPE)

@Retention  作用:表示需要在什么级别保存该注解信息,描述注解的生命周期

@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解 


说回到自定义注解

使用@Interface自定义注解时,自动继承了java.lang.annotation.Annotation接口
要点:
    1.@Interface用来声明一个注解
        格式: public @interface 注解名{定义体}
    2.其中的每一个方法是声明了一个配置参数
        方法名称就是参数名称
        返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)
        可以通过default声明参数中的默认值
        如果只有一个参数成员,一般参数名为value

demo:自定义注解

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


@Target(value= {ElementType.TYPE,ElementType.METHOD})  //表示自定义注解用在类、接口、枚举和方法前面
@Retention(RetentionPolicy.RUNTIME)  //表示自定义注解在运行时有效,可以被反射机制读取
public @interface MyAnnotation {
    String name();  //每一个方法声明了一个配置参数
    int age() default 0;  //方法名就是参数名,默认参数值为0
    String[] schools ();
}

demo:测试自定义注解

public class Demo1 {

    @MyAnnotation(name = "陈",schools={"学校1","学校2"})
    public void show(){}
}

 定义注解和使用注解的意义并不大,如何利用注解实现一些功能呢?

反射操作注解

具体反射的理解可以参考下文

我们在使用注解的时候可能会给参数设置值,提取注解针对的对象是可注解元素,做的其实有两件事: 
1. 确定该元素是否被注解(标记注解只要知道是否被注解就可以了) 
2. 被注解的话获取到注解的参数值

ORM框架都是在实体类的基类里面去实现ORM的功能的,所以我们这里也需要有一个实体类的基类(BaseEntity),我们会在里面提取注解,但我们现在不会在里面实现具体的数据库操作,因为我们这篇文章要讲的内容只是提取注解

以简单的学生类为例

package com.company.demo;

/**
 * 学生类使用自定义注解
 */
@Table("tb_student")
public class Student {
    @FieldAnnotation(columnName = "id", type = "int", length = 10)
    private int id;
    @FieldAnnotation(columnName = "name", type = "varchar2", length = 10)
    private String name;
    @FieldAnnotation(columnName = "id", type = "int", length = 3)
    private int 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;
    }
}

自定义注解1:用来对类进行注解,使得其与数据库表对应

package com.company.demo;
/**
 * 类注解
 */

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(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}

属性注解:和数据表的字段对应

package com.company.demo;
/**
 * 属性注解
 */

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(RetentionPolicy.RUNTIME)
public @interface FieldAnnotation {
    String columnName();
    String type();
    int length();
}

通过反射提取学生类中的注解,生成学生表

 

package com.company.demo;
/**
 * 通过反射操作注解
 */

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

public class Demo01 {
    public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.company.demo.Student");
            //获得类的所有注解
            Annotation[] annotations = clazz.getDeclaredAnnotations();
            for(Annotation a:annotations){
                System.out.println(a);  //@com.company.demo.Table(value=tb_student)
            }
            //获得类的指定注解
            Table t = (Table) clazz.getDeclaredAnnotation(Table.class);
            System.out.println(t.value());  //tb_student
            //获得属性的注解
            Field idField = clazz.getDeclaredField("id");
            FieldAnnotation idAnn = idField.getAnnotation(FieldAnnotation.class);
            System.out.println(idAnn.columnName()+"  "+idAnn.type()+"  "+idAnn.length());
            //之后就可以根据注解信息拼出SQL语句,使用JDBC执行SQL语句,在数据库中生成相关的表
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

 

异常描述: java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:724) at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:531) at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:355) at sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:286) at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:120) at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:72) at java.lang.reflect.Executable.declaredAnnotations(Executable.java:599) at java.lang.reflect.Executable.declaredAnnotations(Executable.java:597) at java.lang.reflect.Executable.getDeclaredAnnotations(Executable.java:588) at java.lang.reflect.Method.getDeclaredAnnotations(Method.java:630) at org.springframework.core.annotation.AnnotationsScanner.getDeclaredAnnotations(AnnotationsScanner.java:453) at org.springframework.core.annotation.AnnotationsScanner.isKnownEmpty(AnnotationsScanner.java:491) at org.springframework.core.annotation.TypeMappedAnnotations.from(TypeMappedAnnotations.java:251) at org.springframework.core.annotation.MergedAnnotations.from(MergedAnnotations.java:351) at org.springframework.core.annotation.MergedAnnotations.from(MergedAnnotations.java:330) at org.springframework.core.annotation.AnnotatedElementUtils.findAnnotations(AnnotatedElementUtils.java:800) at org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation(AnnotatedElementUtils.java:541)怎么解决
03-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值