作用:
格式:
@注释名, 还可添加参数
如:@SuppressWarnings(value="unchecked")
在哪使用?
package com.guanxing.annotation;
import java.awt.*;
//什么是注解
public class Test01 extends Object{
//@Override 重写的注解
@Override
public String toString() {
return super.toString();
}
@Deprecated //不推荐程序员使用,但可以使用.或者存在风险
public static void testDep(){
System.out.println("Deprecated");
}
@SuppressWarnings("all") //镇压警告
public void testSup(){
List list = new List();
}
public static void main(String[] args) {
testDep(); //依旧可以使用
}
}
package com.guanxing.annotation;
import java.lang.annotation.*;
//测试元注解
public class Test02 {
@MyAnnotation //Target定义作用范围有METHOD
public void test01(){
}
}
//定义一个元注解
//Target 表示可作用的地方
@Target(value = {ElementType.METHOD, ElementType.TYPE})
//Retention 表示在什么地方有效
@Retention(value = RetentionPolicy.RUNTIME)
//表示是否将注解生成在javadoc中
@Documented
//表示子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
package com.guanxing.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//自定义注解
public class Test03 {
//注解定义了参数,就要传参,除非有default默认值
// @MyAnnotation2(name = "guanxing")
@MyAnnotation2(name="guanxing")
public void test(){};
}
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型+名称()
//参数名为value的话,使用中可以直接赋值
String name() default "harris";
int age() default 0;
int id() default -1; //如果默认值为-1,代表不存在
String[] schools() default {"华南理工", "中国人大"};
}
原文:https://www.cnblogs.com/straightup/p/14521910.html