Java注解—高级用法与深入解读

import java.lang.annotation.Target;

/**

  • 数据类型使用Demo

*/

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@interface Reference{

boolean next() default false;

}

public @interface AnnotationElementDemo {

//枚举类型

enum Status {FIXED,NORMAL};

//声明枚举

Status status() default Status.FIXED;

//布尔类型

boolean showSupport() default false;

//String类型

String name()default “”;

//class类型

Class<?> testCase() default Void.class;

//注解嵌套

Reference reference() default @Reference(next=true);

//数组类型

long[] value();

}

3、编译器对默认值的限制

编译器对元素的默认值有些过分挑剔。

首先,元素不能有不确定的值。也就是说,元素必须要么具有默认值,要么在使用注解时提供元素的值。其次,对于非基本类型的元素,无论是在源代码中声明,还是在注解接口中定义默认值,都不能以null作为值,这就是限制,没有什么利用可言,但造成一个元素的存在或缺失状态,因为每个注解的声明中,所有的元素都存在,并且都具有相应的值,为了绕开这个限制,只能定义一些特殊的值,例如空字符串或负数,表示某个元素不存在。

4、注解不支持继承

注解是不支持继承的,因此不能使用关键字extends来继承某个@interface,但注解在编译后,编译器会自动继承java.lang.annotation.Annotation接口,这里我们反编译前面定义的DBTable注解。

package com.uncle.annotationdemo;

import java.lang.annotation.Annotation;

//反编译后的代码

public interface DBTable extends Annotation

{

public abstract String name();

}

虽然反编译后发现DBTable注解继承了Annotation接口,请记住,即使Java的接口可以实现多继承,但定义注解时依然无法使用extends关键字继承@interface。

5、快捷方式

所谓的快捷方式就是注解中定义了名为value的元素,并且在使用该注解时,如果该元素是唯一需要赋值的一个元素,那么此时无需使用key=value的语法,而只需在括号内给出value元素所需的值即可。这可以应用于任何合法类型的元素,记住,这限制了元素名必须为value,简单案例如下

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

//定义注解

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@interface IntegerVaule{

int value() default 0;

String name() default “”;

}

//使用注解

public class QuicklyWay {

//当只想给value赋值时,可以使用以下快捷方式

@IntegerVaule(20)

public int age;

//当name也需要赋值时必须采用key=value的方式赋值

@IntegerVaule(value = 10000,name = “MONEY”)

public int money;

}

6、Java内置注解与其它元注解

接着看看Java提供的内置注解,主要有3个,如下:

@Override:用于标明此方法覆盖了父类的方法,源码如下

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.SOURCE)

public @interface Override {

}

@Deprecated:用于标明已经过时的方法或类,源码如下,关于@Documented稍后分析:

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})

public @interface Deprecated {

}

@SuppressWarnnings:用于有选择的关闭编译器对类、方法、成员变量、变量初始化的警告,其实现源码如下:

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})

@Retention(RetentionPolicy.SOURCE)

public @interface SuppressWarnings {

String[] value();

}

其内部有一个String数组,主要接收值如下:

deprecation:使用了不赞成使用的类或方法时的警告;

unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型

(Generics) 来指定集合保存的类型;

fallthrough:当 Switch 程序块直接通往下一种情况而没有 Break时的警告;

path:在类路径、源文件路径等中有不存在的路径时的警告; serial:当在可序列化的类上缺少

serialVersionUID 定义时的警告;

finally:任何 finally 子句不能正常完成时的警告;

all:关于以上所有情况的警告。

这个三个注解比较简单,看个简单案例即可:

//注明该类已过时,不建议使用

@Deprecated

class A{

public void A(){ }

//注明该方法已过时,不建议使用

@Deprecated()

public void B(){ }

}

class B extends A{

@Override //标明覆盖父类A的A方法

public void A() {

super.A();

}

//去掉检测警告

@SuppressWarnings({“uncheck”,“deprecation”})

public void C(){ }

//去掉检测警告

@SuppressWarnings(“uncheck”)

public void D(){ }

}

前面我们分析了两种元注解,@Target和@Retention,除了这两种元注解,Java还提供了另外两种元注解,@Documented和@Inherited,下面分别介绍:

@Documented 被修饰的注解会生成到javadoc中

@Documented

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface DocumentA {

}

//没有使用@Documented

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface DocumentB {

}

//使用注解

@DocumentA

@DocumentB

public class DocumentDemo {

public void A(){

}

}

可以发现使用@Documented元注解定义的注解(@DocumentA)将会生成到javadoc中,而@DocumentB则没有在doc文档中出现,这就是元注解@Documented的作用。

@Inherited 可以让注解被继承,但这并不是真的继承,只是通过使用@Inherited,可以让子类Class对象使用getAnnotations()获取父类被@Inherited修饰的注解,如下:

@Inherited

@Documented

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface DocumentA {

}

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface DocumentB {

}

@DocumentA

class A{ }

class B extends A{ }

@DocumentB

class C{ }

class D extends C{ }

//测试

public class DocumentDemo {

public static void main(String… args){

A instanceA=new B();

System.out.println(“已使用的@Inherited注解:”+Arrays.toString(instanceA.getClass().getAnnotations()));

C instanceC = new D();

System.out.println(“没有使用的@Inherited注解:”+Arrays.toString(instanceC.getClass().getAnnotations()));

}

/**

  • 运行结果:

已使用的@Inherited注解:[@com.zejian.annotationdemo.DocumentA()]

没有使用的@Inherited注解:[]

*/

}

三、注解与反射机制


前面经过反编译后,我们知道Java所有注解都继承了Annotation接口,也就是说 Java使用Annotation接口代表注解元素,该接口是所有Annotation类型的父接口。同时为了运行时能准确获取到注解的相关信息,Java在java.lang.reflect 反射包下新增了AnnotatedElement接口,它主要用于表示目前正在 VM 中运行的程序中已使用注解的元素,通过该接口提供的方法可以利用反射技术地读取注解的信息,如反射包的Constructor类、Field类、Method类、Package类和Class类都实现了AnnotatedElement接口,它简要含义如下:

  • Class:类的Class对象定义

  • Constructor:代表类的构造器定义

  • Field:代表类的成员变量定义

  • Method:代表类的方法定义

  • Package:代表类的包定义

下面是AnnotatedElement中相关的API方法,以上5个类都实现以下的方法

| 返回值 | 方法名称 | 说明 |

| — | — | — |

| | getAnnotation(Class annotationClass) | 该元素如果存在指定类型的注解,则返回这些注解,否则返回 null。 |

| Annotation[] | getAnnotations() | 返回此元素上存在的所有注解,包括从父类继承的 |

| boolean | isAnnotationPresent(Class<? extends Annotation> annotationClass) | 如果指定类型的注解存在于此元素上,则返回 true,否则返回 false。 |

| Annotation[] | getDeclaredAnnotations() | 返回直接存在于此元素上的所有注解,注意,不包括父类的注解,调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响,没有则返回长度为0的数组 |

简单案例演示如下:

import java.lang.annotation.Annotation;

import java.util.Arrays;

/**

  • Created by zejian on 2017/5/20.

  • Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]

*/

@DocumentA

class A{ }

//继承了A类

@DocumentB

public class DocumentDemo extends A{

public static void main(String… args){

Class<?> clazz = DocumentDemo.class;

//根据指定注解类型获取该注解

DocumentA documentA=clazz.getAnnotation(DocumentA.class);

System.out.println(“A:”+documentA);

//获取该元素上的所有注解,包含从父类继承

Annotation[] an= clazz.getAnnotations();

System.out.println(“an:”+ Arrays.toString(an));

//获取该元素上的所有注解,但不包含继承!

Annotation[] an2=clazz.getDeclaredAnnotations();

System.out.println(“an2:”+ Arrays.toString(an2));

//判断注解DocumentA是否在该元素上

boolean b=clazz.isAnnotationPresent(DocumentA.class);

System.out.println(“b:”+b);

/**

  • 执行结果:

A:@com.zejian.annotationdemo.DocumentA()

an:[@com.zejian.annotationdemo.DocumentA(), @com.zejian.annotationdemo.DocumentB()]

an2:@com.zejian.annotationdemo.DocumentB()

b:true

*/

}

}

四、运行时注解处理器


了解完注解与反射的相关API后,现在通过一个实例来演示利用运行时注解来组装数据库SQL的构建语句的过程

/**

  • 表注解

*/

@Target(ElementType.TYPE)//只能应用于类上

@Retention(RetentionPolicy.RUNTIME)//保存到运行时

public @interface DBTable {

String name() default “”;

}

/**

  • 注解Integer类型的字段

*/

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public @interface SQLInteger {

//该字段对应数据库表列名

String name() default “”;

//嵌套注解

Constraints constraint() default @Constraints;

}

/**

  • 注解String类型的字段

*/

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public @interface SQLString {

//对应数据库表的列名

String name() default “”;

//列类型分配的长度,如varchar(30)的30

int value() default 0;

Constraints constraint() default @Constraints;

}

/**

  • 约束注解

*/

@Target(ElementType.FIELD)//只能应用在字段上

@Retention(RetentionPolicy.RUNTIME)

public @interface Constraints {

//判断是否作为主键约束

boolean primaryKey() default false;

//判断是否允许为null

boolean allowNull() default false;

//判断是否唯一

boolean unique() default false;

}

/**

  • 数据库表Member对应实例类bean

*/

@DBTable(name = “MEMBER”)

public class Member {

//主键ID

@SQLString(name = “ID”,value = 50, constraint = @Constraints(primaryKey = true))

private String id;

@SQLString(name = “NAME” , value = 30)

private String name;

@SQLInteger(name = “AGE”)

private int age;

@SQLString(name = “DESCRIPTION” ,value = 150 , constraint = @Constraints(allowNull = true))

private String description;//个人描述

//省略set get…

}

上述定义4个注解,分别是@DBTable(用于类上)、@Constraints(用于字段上)、 @SQLString(用于字段上)、@SQLString(用于字段上)并在Member类中使用这些注解,这些注解的作用的是用于帮助注解处理器生成创建数据库表MEMBER的构建语句,在这里有点需要注意的是,我们使用了嵌套注解@Constraints,该注解主要用于判断字段是否为null或者字段是否唯一。必须清楚认识到上述提供的注解生命周期必须为@Retention(RetentionPolicy.RUNTIME),即运行时,这样才可以使用反射机制获取其信息。有了上述注解和使用,剩余的就是编写上述的注解处理器了,前面我们聊了很多注解,其处理器要么是Java自身已提供、要么是框架已提供的,我们自己都没有涉及到注解处理器的编写,但上述定义处理SQL的注解,其处理器必须由我们自己编写了,如下

import java.lang.annotation.Annotation;

import java.lang.reflect.Field;

import java.util.ArrayList;

import java.util.List;

/**

  • 运行时注解处理器,构造表创建语句

*/

public class TableCreator {

public static String createTableSql(String className) throws ClassNotFoundException {

Class<?> cl = Class.forName(className);

DBTable dbTable = cl.getAnnotation(DBTable.class);

//如果没有表注解,直接返回

if(dbTable == null) {

System.out.println(

"No DBTable annotations in class " + className);

return null;

}

String tableName = dbTable.name();

// If the name is empty, use the Class name:

if(tableName.length() < 1)

tableName = cl.getName().toUpperCase();

List columnDefs = new ArrayList();

//通过Class类API获取到所有成员字段

for(Field field : cl.getDeclaredFields()) {

String columnName = null;

//获取字段上的注解

Annotation[] anns = field.getDeclaredAnnotations();

if(anns.length < 1)

continue; // Not a db table column

//判断注解类型

if(anns[0] instanceof SQLInteger) {

SQLInteger sInt = (SQLInteger) anns[0];

//获取字段对应列名称,如果没有就是使用字段名称替代

if(sInt.name().length() < 1)

columnName = field.getName().toUpperCase();

else

columnName = sInt.name();

//构建语句

columnDefs.add(columnName + " INT" +

getConstraints(sInt.constraint()));

}

//判断String类型

if(anns[0] instanceof SQLString) {

SQLString sString = (SQLString) anns[0];

// Use field name if name not specified.

if(sString.name().length() < 1)

columnName = field.getName().toUpperCase();

else

columnName = sString.name();

columnDefs.add(columnName + " VARCHAR(" +

sString.value() + “)” +

getConstraints(sString.constraint()));

}

}

//数据库表构建语句

StringBuilder createCommand = new StringBuilder(

"CREATE TABLE " + tableName + “(”);

for(String columnDef : columnDefs)

createCommand.append("\n " + columnDef + “,”);

// Remove trailing comma

String tableCreate = createCommand.substring(

0, createCommand.length() - 1) + “);”;

return tableCreate;

}

/**

  • 判断该字段是否有其他约束

  • @param con

  • @return

*/

private static String getConstraints(Constraints con) {

String constraints = “”;

if(!con.allowNull())

constraints += " NOT NULL";

if(con.primaryKey())

constraints += " PRIMARY KEY";

if(con.unique())

constraints += " UNIQUE";

return constraints;

}

public static void main(String[] args) throws Exception {

String[] arg={“com.zejian.annotationdemo.Member”};

for(String className : arg) {

System.out.println("Table Creation SQL for " +

className + " is :\n" + createTableSql(className));

}

/**

  • 输出结果:

Table Creation SQL for com.zejian.annotationdemo.Member is :

CREATE TABLE MEMBER(

ID VARCHAR(50) NOT NULL PRIMARY KEY,

NAME VARCHAR(30) NOT NULL,

AGE INT NOT NULL,

DESCRIPTION VARCHAR(150)

);

*/

}

}

如果对反射比较熟悉的同学,上述代码就相对简单了,我们通过传递Member的全路径后通过Class.forName()方法获取到Member的class对象,然后利用Class对象中的方法获取所有成员字段Field,最后利用field.getDeclaredAnnotations()遍历每个Field上的注解再通过注解的类型判断来构建建表的SQL语句。这便是利用注解结合反射来构建SQL语句的简单的处理器模型,是否已回想起Hibernate?

五、Java 8中注解增强


1、元注解@Repeatable

元注解@Repeatable是JDK1.8新加入的,它表示在同一个位置重复相同的注解。在没有该注解前,一般是无法在同一个类型上使用相同的注解的

//Java8前无法这样使用

@FilterPath(“/web/update”)

@FilterPath(“/web/add”)

public class A {}

Java8前如果是想实现类似的功能,我们需要在定义@FilterPath注解时定义一个数组元素接收多个值如下

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

public @interface FilterPath {

String [] value();

}

//使用

@FilterPath({“/update”,“/add”})

public class A { }

但在Java8新增了@Repeatable注解后就可以采用如下的方式定义并使用了

import java.lang.annotation.*;

//使用Java8新增@Repeatable原注解

@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Repeatable(FilterPaths.class)//参数指明接收的注解class

public @interface FilterPath {

String value();

}

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@interface FilterPaths {

FilterPath[] value();

}

//使用案例

@FilterPath(“/web/update”)

@FilterPath(“/web/add”)

@FilterPath(“/web/delete”)

class AA{ }

我们可以简单理解为通过使用@Repeatable后,将使用@FilterPaths注解作为接收同一个类型上重复注解的容器,而每个@FilterPath则负责保存指定的路径串。为了处理上述的新增注解,Java8还在AnnotatedElement接口新增了getDeclaredAnnotationsByType() 和 getAnnotationsByType()两个方法并在接口给出了默认实现,在指定@Repeatable的注解时,可以通过这两个方法获取到注解相关信息。但请注意,旧版API中的getDeclaredAnnotation()和 getAnnotation()是不对@Repeatable注解的处理的(除非该注解没有在同一个声明上重复出现)。注意getDeclaredAnnotationsByType方法获取到的注解不包括父类,其实当 getAnnotationsByType()方法调用时,其内部先执行了getDeclaredAnnotationsByType方法,只有当前类不存在指定注解时,getAnnotationsByType()才会继续从其父类寻找,但请注意如果@FilterPath和@FilterPaths没有使用了@Inherited的话,仍然无法获取。下面通过代码来演示:

//使用Java8新增@Repeatable原注解

@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

@Repeatable(FilterPaths.class)

public @interface FilterPath {

String value();

}

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@interface FilterPaths {

FilterPath[] value();

}

@FilterPath(“/web/list”)

class CC { }

//使用案例

@FilterPath(“/web/update”)

@FilterPath(“/web/add”)

@FilterPath(“/web/delete”)

class AA extends CC{

public static void main(String[] args) {

Class<?> clazz = AA.class;

//通过getAnnotationsByType方法获取所有重复注解

FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);

FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);

if (annotationsByType != null) {

for (FilterPath filter : annotationsByType) {

System.out.println(“1:”+filter.value());

}

}

System.out.println(“-----------------”);

if (annotationsByType2 != null) {

for (FilterPath filter : annotationsByType2) {

System.out.println(“2:”+filter.value());

}

}

System.out.println(“使用getAnnotation的结果:”+clazz.getAnnotation(FilterPath.class));

/**

  • 执行结果(当前类拥有该注解FilterPath,则不会从CC父类寻找)

1:/web/update

1:/web/add

1:/web/delete


2:/web/update

2:/web/add

2:/web/delete

使用getAnnotation的结果:null

*/

}

}

从执行结果来看如果当前类拥有该注解@FilterPath,则getAnnotationsByType方法不会从CC父类寻找,下面看看另外一种情况,即AA类上没有@FilterPath注解

//使用Java8新增@Repeatable原注解
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

面试结束复盘查漏补缺

每次面试都是检验自己知识与技术实力的一次机会,面试结束后建议大家及时总结复盘,查漏补缺,然后有针对性地进行学习,既能提高下一场面试的成功概率,还能增加自己的技术知识栈储备,可谓是一举两得。

以下最新总结的阿里P6资深Java必考题范围和答案,包含最全MySQL、Redis、Java并发编程等等面试题和答案,用于参考~

重要的事说三遍,关注+关注+关注!

历经30天,说说我的支付宝4面+美团4面+拼多多四面,侥幸全获Offer

image.png

更多笔记分享

历经30天,说说我的支付宝4面+美团4面+拼多多四面,侥幸全获Offer

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
}

从执行结果来看如果当前类拥有该注解@FilterPath,则getAnnotationsByType方法不会从CC父类寻找,下面看看另外一种情况,即AA类上没有@FilterPath注解

//使用Java8新增@Repeatable原注解
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。[外链图片转存中…(img-TIoeP80d-1713167652888)]

[外链图片转存中…(img-7yyDzDvV-1713167652889)]

[外链图片转存中…(img-zfggNBfs-1713167652889)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注Java获取)

img

面试结束复盘查漏补缺

每次面试都是检验自己知识与技术实力的一次机会,面试结束后建议大家及时总结复盘,查漏补缺,然后有针对性地进行学习,既能提高下一场面试的成功概率,还能增加自己的技术知识栈储备,可谓是一举两得。

以下最新总结的阿里P6资深Java必考题范围和答案,包含最全MySQL、Redis、Java并发编程等等面试题和答案,用于参考~

重要的事说三遍,关注+关注+关注!

[外链图片转存中…(img-JO0T0ha6-1713167652889)]

[外链图片转存中…(img-x0uPomyY-1713167652890)]

更多笔记分享

[外链图片转存中…(img-oOb0s85v-1713167652890)]

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

  • 8
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值