Files
team-learning-program/Java/10.注解.md
T
tensorflow-jumao 806de33657 更新
2021-07-10 01:50:21 +08:00

125 lines
3.3 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 10. 注解
## 10.1 什么是注解
注解,一种元数据形式,提供有关程序的数据,该数据不属于程序本身。注释对其注释的代码的操作没有直接影响。
注解的语法:
```java
@注解类型名
```
注释有多种用途,其中包括:
* 编译前:为编译器提供编译检查的依据,辅助检查代码错误或抑制检查异常。
* 编译中或发布时:给编译器提供信息生成代码或给其他工具提供信息生成文档等。
* 运行时:在运行过程中提供信息给解释器,辅助程序执行。
* 注解经常和反射结合起来用,多用于框架中。
## 10.2 内置的注解
### 10.2.1 Override
* 加在方法前
* 表示重写(覆盖)父类的方法;
* 如果重写(覆盖)有错误,则报错。
* 因此重写父类方法,请加上@Override注解
```java
class Parent {
String name;
public Parent(){}
public Parent(String name)
{
this.name = name;
}
public void sayHello()
{
System.out.println("你好,我是" + name )
}
}
public class Child extends Parent
{
String name;
public Child{}
@Override
public void sayHello(String str)
{
//这里会报错
super.sayHello();
System.out.println("Hello,im Datawhale");
}
}
/**
本段代码则不会提示错误
public class Child extends Parent
{
String name;
public Child{}
@Override
public void sayHello()
{
super.sayHello();
System.out.println("Hello,im Datawhale");
}
}
**/
```
## 10.3 自定义注解
日常开发中我们使用class、interface比较多,而注解和它们一样,也是一种类的类型,他是用的修饰符为 @interface @元注解
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,语法如下:
```java
public @interface MyTestAnnotation {
注解属性 [default 默认值]
}
```
## 10.4 元注解
元注解负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。
@Target,
@Retention,
@Documented,
@Inherited
@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。
 取值(ElementType)有:
  1.CONSTRUCTOR:用于描述构造器
  2.FIELD:用于描述域
  3.LOCAL_VARIABLE:用于描述局部变量
  4.METHOD:用于描述方法
  5.PACKAGE:用于描述包
  6.PARAMETER:用于描述参数
  7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
```java
@Target(ElementType.TYPE)
public @interface Table {
}
@Target(ElementType.FIELD)
public @interface NoDBColumn {
}
```
@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。