您的位置 首页 java

java必学核心知识总结——注解

前言

前几年我们的项目还在structs 2 上跑,有一次问一个同事是否知道Spring Boot,同事说那不是用注解来开发的吗。虽然这个答案并不完全对,但是从客观上Spring Boot对刚刚接触它的人来说最醒目的就是注解了。那么今天我们来了解一下 java 语言的核心功能——注解。

注解是什么

public @interface Anno {
}
 

以上就是一个最简单的注解声明。它可以注释到类、接口、方法以及变量上。通过向方法,接口,类或字段添加注释,为其绑定的源代码分配额外的元数据。

注解的用途

通过注解我们可以通知编译器有关警告和错误的信息在编译时操作源代码在运行时修改或检查行为。jdk提供内置5个基本注解来处理代码检查。

  • @Override 来标记该方法重写或替换继承的方法的行为。如果你重写了父类方法不带该注解会触发一些警告。
  • @SuppressWarnings 表示我们要忽略部分代码中的某些警告。如忽略潜在的类型不安全转换警告unchecked。
  • @Deprecated 用来表示类、方法已经过时,不推荐使用。如果你强行使用编译器会在编译时进行警告。
  • @Safevarargs 抑制“堆污染”警告。“堆污染”指的是将一个不带 泛型 的对象赋给带泛型的变量时引发的类型问题。如果你不想看到该警告就可以使用该注解来抑制。
  • @FunctionalInterface java 8 新增注解,只能作用于接口上来标识该接口是函数式接口。java中函数式接口表示该接口只能有一个抽象方法。如果一个接口被此注解修饰,添加第二个抽象方法将无法通过编译。

注解可以将一些元数据传递给你编写的逻辑。比如Spring Mvc 中的一个常用注解@RequestMapping,我们可以通过value参数来传递一个path路径,Spring Mvc通过对请求的路径的匹配来作出是否路由到该path上。 目前大量的的框架都依赖注解,比如Spring、hibernate、dubbo等等。

元注解

元注解是可以应用于其他注解的注解。来增强或者配置目标注解的机制。jdk目前提供了5个元注解。如果你需要开发自定义注解,请务必熟悉它们:

  • @Retention 只能用于修饰注解,来指定被修饰注解可以保留多长时间。规定了三种策略:

RetentionPolicy.SOURCE 这种策略下被修饰的注解只能存在于源代码中,编译后被丢弃,通过反射无法获取到被修饰的注解。

RetentionPolicy.CLASS 这种策略下被修饰的注解会被编译进 字节码 文件中。但是JVM无法获取到被修饰的注解。这是一个默认值,当你声明的注解没有添加任何保留策略时,会默认指定该策略。

RetentionPolicy.RUNTIME 这种策略下被修饰的注解不但可以编译进字节码文件。而且JVM也可以获取被该注解修饰的注解。而且程序编码也可以通过反射来获取被该注解修饰的注解的一些元信息。

  • @Target 用于指定被修饰注解的修饰目标类型。如果一个注解明确了可修饰的目标类型,则只能修饰指定的类型。由枚举ElementType来规定。

– TYPE 只能修饰 类、接口、枚举。

– FIELD 只能修饰成员变量,包含枚举内的常量。

– METHOD 只能修饰方法。

– PARAMETER 只能修饰参数。

– CONSTRUCTOR 只能修饰构造器。

– LOCAL_VARIABLE 只能修饰局部变量。

Annotation _TYPE 只能修饰注解。

– PACKAGE 只能修饰包定义。也就是package-info.java中

– TYPE_PARAMETER java 8 新增 表示该注解能写在类型参数的声明语句中。 类型参数声明如: <T>、<T extends Person>

– TYPE_USE java 8 新增 注解可以再任何用到类型的地方使用。

  • @Documented 被该注解修饰的注解可以被javadoc工具提取为文档。
  • @Inherited 被该注解修饰的注解有继承性。这里要注意一些要点首先这种继承性体现的类之间而不是接口之间,而且注解必须是对JVM可见。也就是@Retention为RetentionPolicy.RUNTIME 才起作用。
  • @Repeatable java 8 新增。在此之前在同一个元素上同一个注解只能出现一次。@Repeatable可以让一个注解多次出现在一个元素上。

自定义注解

自定义注解跟自定义接口类似,但是还有一些区别,实际开发你需要对自定义注解进行元注解注释。注解中的成员变量以无参抽象方法来声明,成员变量并不是所有类型都支持,目前只支持以下类型:

  • 所有基本类型(int,float,boolean,byte,double,char,long,short)
  • String
  • Class (如:Class<?> 或 Class<T>)
  • enum java枚举
  • Annotation

下面我们就来自定义一个注解:

 /**
 * 声明一个可以标记在类、接口、枚举、方法上的注解。
 * 并且JVM Runtime 可见、可生成文档
 *
 * @author Dax
 * @since 17 :27 2019/9/4
 */@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Anno {
 /**
 * 若方法名为value且注解声明只需要声明value属性时,
 * value可以省略, @Anno("anno") 等同于 @Anno(value="anno")
 *
 * @return the string
 */ String value();
 /**
 * 一个具有默认值的 String 类型属性。
 * name若不显式声明,则默认值为"" 。
 * 声明默认值通过 default + 默认值 来声明
 *
 * @return the string
 */ String name() default "";
 /**
 * 一个Class 类型属性,没有默认值。其他支持类型不再举例
 *
 * @return the class
 */ Class<?> clazz();
}
 

获取注解中的元数据

所有的注解都是java.lang.annotation.Annotation 的子类。

只有RetentionPolicy为RUNTIME的 注解才能通过反射获取。在反射包中提供了AnnotatedElement 接口来对元素上的可捕捉到的注解进行处理。该接口是Class、Method、Constructor等程序元素对象的父接口。也就是说只要能获取程序元素对象就能对其存在的注解进行处理。主要方法有:

  • boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 判断是否存在 annotationClass类型的注解。
  • <T extends Annotation> T getAnnotation(Class<T> annotationClass) 如果在当前元素上存在参数所指定类型(annotationClass)的注解,则返回对应的注解,否则将返回null。
  • Annotation[] getAnnotations() 返回在这个元素上的所有注解。如果该元素没有注解,则返回值是长度为0的数组。该方法的调用者可以自由地修改返回的数组;它不会对返回给其他调用者的数组产生影响。
  • <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) 返回与该元素相关联的注解。如果没有与此元素相关联的注解,则返回值是长度为0的数组。这个方法与getAnnotation(Class)的区别在于,该方法检测其参数是否为可重复的注解类型(JLS 9.6),如果是,则尝试通过“looking through”容器注解来查找该类型的一个或多个注解。该方法的调用者可以自由地修改返回的数组;它不会对返回给其他调用者的数组产生影响。参考@Repeatable。
  • <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) 如果参数中所指定类型的注解是直接存在于当前元素上的,则返回对应的注解,否则将返回null。这个方法忽略了继承的注解。(如果没有直接在此元素上显示注释,则返回null。)
  • <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) 可获取重复注解但是忽略掉继承注解。
  • Annotation[] getDeclaredAnnotations() 跟上面的注解区别在于不能获取重复注解。

基本上对这个接口的方法进行学习后就可以知道如何获取注解的元数据了。下面我们写一个例子,还是上面的Anno注解为例:

/**
 * 被注解标记的类
 **/@Anno("hello")
public class  Foo  {}
/**
 * 通过获取Foo 的Class 类,
 * 然后就可以根据上面已经介绍的方法来获取value的值了
 * @author dax
 * @since 2019/9/4 22:17
 */public class Main {
 public static void main(String[] args) {
 Anno annotation = Foo.class.getAnnotation(Anno.class);
 String value = annotation.value();
 System.out.println("value = " + value);
 }
}
 

总结

今天我们系统地对注解进行了归纳,相信你已经对注解有了系统性的认识。其实注解还可以干一些花式操作,比如lombok框架。后面我们会介绍相关的注解技术,多多关注。

文章来源:智云一二三科技

文章标题:java必学核心知识总结——注解

文章地址:https://www.zhihuclub.com/181678.shtml

关于作者: 智云科技

热门文章

评论已关闭

14条评论

  1. I don t think that the ANA is having any affect on your lack of pregnancy at this time 5 mg ml n 5, and ovariectomy increased the protein concentration in EIU to 7

  2. naprelan puedo comprar citalopram sin receta As for whether he knew what she had planned for her now legendary performance, Cyrus would only say, I knew that she wanted to do something really special and something everyone was going to be talking about

  3. First, we transformed ORs, RRs, or HRs and their CIs to their natural logarithms and SEs The estrogen and progesterone receptor values may help to predict whether adjuvant Tamoxifen Citrate Actavis tamoxifen citrate therapy is likely to be beneficial

  4. I have had the similar feeling randomly in the past not while on anything and have always had more fat on my chest then I would like so I am not sure if its puberty gyno or not, when my nipples are hard everything looks good, when not i think its a little fat I cannot feel any lumps

  5. From the sound of it RF9 could act as a more potent replacement for kisspeptin, particularly if it does have both kisspeptin agonism and GnIH antagonism

  6. Impact of blockade of histamine H2 receptors on chronic heart failure revealed by retrospective and prospective randomized studies

  7. 1102; AARP Retired Persons Group Suports FDA Regulation of Food Supplements 124, p However, overall quality of life did not differ between the two arms, and no significant differences in new onset osteoporosis, clinical skeletal fractures, cardiovascular events, or other malignancies were seen

  8. A second study the first was the CALGB study reported at ASCO in 1998 showing a benefit to the addition of Taxol to an anthracycline based adjuvant regimen, was reported from the M

  9. Do you think I need any PCT in there somewhere, or is switching off to LGD for that 4 weeks sufficient

  10. You might notice that it worsens as you go higher or when you cough, push yourself hard, or bend over

网站地图