注解
注解 Annotation
- 不是程序本身,对程序做出解释
- 可以被其他程序(如编译器)读取
package test3;
public class AnnotationDemo extends Object{
@Override //重写的注释
public String toString() {
return super.toString();
}
}
内置注解:
@ Override:定义在 java. lang Override中,此注释只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明。
@ Deprecated:定义在 Java. lang. Deprecated中,此注释可以用于修辞方法,属性,类,表示不鼓励程序员使用这样的元素,通常是因为它很危险或者存在更好的选择。
@ SuppressWarnings:定义在 Java. lang. SuppressWarnings中,用来抑制编译时的警告信息。
与前两个注释有所不同,你需要添加一个参数才能正确使用,这些参数都是已经定义好了的,我们选择性的使用就好了。
@SuppressWarnings ( "all")
@SuppressWarnings ("unchecked")
@SuppressWarnings(value={"unchecked", "deprecation"})
……
public class AnnotationDemo extends Object{
@Override //重写的注解
public String toString() {
return super.toString();
}
@Deprecated
public static void test(){
System.out.println("Deprecated");
}
@SuppressWarnings("all")
public void test01(){
List<String> list=new ArrayList<>();
}
public static void main(String[] args) {
test();
}
}
自定义注解:
-
元注解:meta-annotation 注解其他注解
(@Target,@Retention,@Documented, @Inherited)
@ Target:用于描述注解的使用范围(即被描述的注解可以用在什么地方)。
@ Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期。--->SOURCE < CLASS < RUNTIME
@ Document:说明该注解将被包含在 Javadoc中。
@ Inherited:说明子类可以继承父类中的该注解。
public class AnnotationDemo {
@MyAnnotation
public void test(){
}
}
//自定义一个注解
@Target(value= ElementType.METHOD)
@Retention(value= RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation{
}
public class AnnotationDemo {
// 注解可以显示赋值,如果没有默认值,就必须给注解赋值
@MyAnnotation2(name="邓孝慈")
public void test(){
}
//如果没有默认值,就必须给注解赋值
@MyAnnotation3("许魏洲")
public void test1(){
}
}
//自定义一个注解
@Target(value= ElementType.METHOD)
@Retention(value= RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation2{
// 注解的参数: 参数类型 + 参数名()
String name() default "";
int age() default 0;
int id() default -1; //-1代表不存在
String[] schools() default {"哈哈","嘿嘿"};
}
@Target(value=ElementType.METHOD)
@Retention(value= RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
浙公网安备 33010602011771号