什么是注解
package hike.annotation;
import java.util.ArrayList;
import java.util.List;
// 什么是注解
public class Test01 extends Object {
// @Override 重写的注解
@Override
public String toString() {
return super.toString();
}
// Deprecated 不推荐程序员使用,但是可以使用,或者存在更好的方式
@Deprecated
public static void test() {
System.out.println("Deprecated");
}
// 镇压注解 把各种方法名,类名,变量名 的 所在区域 的提示颜色 给处理掉
@SuppressWarnings("all")
public static void test02() {
List list = new ArrayList();
}
public static void main(String[] args) {
test();
}
}
元注解
package hike.annotation;
import javax.xml.bind.Element;
import java.lang.annotation.*;
// 测试元注解
public class Test02 {
}
// 定义一个注解
@Target(value = {ElementType.METHOD, ElementType.TYPE})
// Retention 表示我们的注解在什么地方还有效
// runtime(运行时)>class(类)>sources(源码)
@Retention(value = RetentionPolicy.RUNTIME)
// Document 表示是否将我们的注解生成在JavaDoc中
@Documented
// Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
// Target 表示我们的注解可以用在哪些地方
自定义注解
package hike.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义注解
public class Test03 {
// 注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
// 如果有默认值,可以不写
@MyAnnotation2(name = "hike")
public static void test(){}
// 如果注解只有一个参数,且这个参数名 是 value() 时,调用这个注解的时候,可以省略value()参数 不写
// 如果主页只有一个参数,且这个参数名 不是 value() 时,那么参数名必须写
@MyAnnotation3("hike")
public static void test3() {}
// Ps. 注解的读取,通过反射的方式读取
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
// 注解的参数:参数类型 + 参数名+();
String name() default "";
int age() default 0;
int id() default -1; // 如果默认值为-1,代表不存在
String[] schools() default {"一本", "二本"};
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}