Java注解通俗易懂
2020-07-01 本文已影响0人
info_gu
注解
可以被程序识别的注释
1.1 元注解
package com.lcy.annotation;
import java.lang.annotation.*;
//测试原注解
@MyAnnotation
public class Test01 {
public void test() {
}
}
//定义一个注解
//Target 表示我们的注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么地方有效 runtime>class>source
@Retention(value = RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生成在JAVAdoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
1.2 内置注解
package com.lcy.annotation;
import java.util.ArrayList;
//内置注解
public class Test03 {
@Override //重写的注解
public String toString() {
return "Test03{}";
}
@Deprecated //不推荐使用,存在更好的
public static void test() {
System.out.println("Deprecated");
}
@SuppressWarnings("all") //镇压警告
public void test2() {
ArrayList arrayList = new ArrayList();
}
public static void main(String[] args) {
test();
}
}
1.3 自定义注解
package com.lcy.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义注解 带参数和不带参数
public class Test02 {
//注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
@MyAnnotation2(name = "陈平安",schools = "清华")
public void test() {
}
@My3("宁姚")
public void test2() {
}
}
@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 My3{
String value();
}