什么是注解
//什么是注解
//所有的类默认继承Object
public class Test01 extends Object {
//@Override 这就是重写的注解
@Override
public String toString() {
return super.toString();
}
}
内置注解
@Deprecated
// Deprecated 废弃的,已经过时的,不推荐使用,或许存在更好的方法
@Deprecated
public static void test(){
System.out.println("Deprecated");
}
@SuppressWarnings
// 镇压警告 平时不建议使用镇压警告,警告可以帮助我们查看程序的错误
@SuppressWarnings("all")
public void test2(){
List list = new ArrayList();
}
元注解
Target 可以表示注解用在什么地方,注解的范围
ElementType.METHOD在方法上使用
ElementType.TYPE 在类上使用
Retention 表示我们的注解在什么地方还有效
RetentionPolicy.RUNTIME 运行时
RetentionPolicy.CLASS 类中
RetentionPolicy.SOURCE 源码中
RUNTIME>CLASS>SOURCE
//测试元注解
public class Test02 {
@Myannotation
public void test(){
}
}
//Target 可以表示注解用在什么地方
//ElementType.METHOD在方法上使用
//ElementType.TYPE 在类上使用
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么地方还有效
//RetentionPolicy.RUNTIME 运行时
//RetentionPolicy.CLASS 类中
//RetentionPolicy.SOURCE 源码中
//RUNTIME>CLASS>SOURCE
@Retention(value = RetentionPolicy.SOURCE)
//Documented 表示是否将我们的注解生产在JAVADoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
//定义一个注解
@interface Myannotation {
}
自定义注解
//自定义注解
public class Test03 {
@Myannotation2(name = "tom")
public void test(){
}
@Myannotation3("")//只有一个值,用value定义,这里可以省略
public void test3(){
}
}
//注解的范围
@Target({ElementType.TYPE,ElementType.METHOD})
//运行时有效
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation2{
// 注解的参数:参数类型+参数名()
String name();//这不是方法
int age() default 0;//默认值
int id() default -1;//如果为-1,表示找不到
String [] arr() default {"清华大学","信息工程学院"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Myannotation3{
String value();
}