java注解——内置注解和四种元注解

java 内置注解:

@Override(重写方法):被用于标注方法,用于说明所标注的方法是重写父类的方法

@Deprecated(过时方法):用于说明所标注元素,因存在安全问题或有更好选择而不鼓励使用,如果强行使用,则编译器会发出警告

@SuppressWarnings(消除警告):用于取消编辑器所显示的警告,有如下属性值

——deprecation:使用已被 @Deprecated 标注的程序元素

Date date = new Date();
//消除警报
@SuppressWarnings("deprecation")
int hour = date.getHours();// 该方法以被弃用
System.out.println(hour);

——unused:程序含有未被使用的元素

——serial:在可序列化的类上缺少 serialVersionUID 定义

 

自定义注解:

注释属性默认没有默认值,在后面加 default 设置默认值

public @interface Service {
String value() </span><span style="color: rgba(0, 0, 255, 1)">default</span> ""<span style="color: rgba(0, 0, 0, 1)">;

</span><span style="color: rgba(0, 0, 255, 1)">int</span> version() <span style="color: rgba(0, 0, 255, 1)">default</span> 0<span style="color: rgba(0, 0, 0, 1)">;

}

 

元注解:java 提供了四个用于修饰自定义注解的元注解

@Target:用于指定被修饰的自定义注解只能用于修饰程序中哪些元素,有四个常用属性

@Retention:用于指定被修饰的自定义注解可以保留多久,有三个常用属性

@Documented:执行 javadoc 命令时,被该元注解修饰的自定义注解也会生成在文档中

@Inherited:如果父类所使用的注解有此修饰,则子类可以继承该注解,否则不能

//TYPE 用于类、接口或者枚举声明
//FIELD 用于全局属性
//METHOD 用于方法
//PARAMETER 用于方法的参数
@Target({ElementType.TYPE,ElementType.FIELD})//数组时,一个值不用写 {}

//SOURCE 源码
//CLASS 编译器
//RUNTIME 运行
@Retention(RetentionPolicy.RUNTIME)

//生成的文档是否含有此注释
@Documented

//子类会继承此类上的注释(不继承类里的)
@Inherited
public @interface Service {

String value() </span><span style="color: rgba(0, 0, 255, 1)">default</span> ""<span style="color: rgba(0, 0, 0, 1)">;

</span><span style="color: rgba(0, 0, 255, 1)">int</span> version() <span style="color: rgba(0, 0, 255, 1)">default</span> 0<span style="color: rgba(0, 0, 0, 1)">;

}