Java注解
- 和注释一样,注解不是程序本身,而是对程序作出解释,而注解与注释不同的点在于,注解可以被其他程序比如编译器读取
@Override//重写注解
@Deprecated//不推荐使用注解,可以使用但是又风险或者有更好的方式
@SuppressWarnings//“镇压”警告注解
元注解
元注解的作用解释注解其他注解,Java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型做说明
4个元注解分别为:
@Target:用于描述注解的使用范围
@Retention:用于表示需要在什么级别保存注解信息,用于描述注解的声明周期,(SOURCE<CLASS<RUNTIME)
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
测试元注解,
package com.bowenxu;
import java.lang.annotation.*;
//测试元注解
public class test01 {
@Override
public String toString() {
return super.toString();
}
//手写一个注解,测试一下元注解
@Target(value = {ElementType.METHOD,ElementType.FIELD})//用于描述注解的使用范围
@Retention(value = RetentionPolicy.RUNTIME) //用于描述注解的声明周期 (SOURCE源码<CLASS文件<RUNTIME运行时)
@Documented //用于说明该注解被包含在Javadoc中
@Inherited //用于说明该注解可以被子类继承
@interface myAnnotation{
}
//测试自定义注解
@myAnnotation
public void test02(){
}
@myAnnotation
private String field;
}
自定义注解
package com.bowenxu;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class test02 {
@myAnnotation("只有一个参数,可以声明成value,这样使用时就可以省略value")
public void test01(){}
@myAnnotation2(name = "有defalut默认值的可以不传参数,没有的必须显示的传参数")
public void test02(){}
@myAnnotation3
public void test03(){}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface myAnnotation{
//定义注解参数的语法 类型+参数名+()
String value();
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface myAnnotation2{
String name();
int id() default -1;
}
@interface myAnnotation3{
String name() default "蜡笔小新";
int id() default -1;
int age() default 18;
String sex() default "男";
String[] hobby() default "电影,美女";
}