Java基础巩固系列 注解(Annotation)
概述:
基本的Annotation
自定义Annotation:
提取Annotation信息:
元注解:
元注解@Retention的相关介绍:
元注解@Target的相关介绍:
TestAnnotation 代码示例:
/** * 注解 * 1.JDK提供的常用的注解 * @Override: 限定重写父类方法, 该注释只能用于方法 * @Deprecated: 用于表示某个程序元素(类, 方法等)已过时 * @SuppressWarnings: 抑制编译器警告 * 2.如何定义一个注解 * 3.元注解 */ public class TestAnnotation { public static void main(String[] args) { Person p = new Student(); p.walk(); p.eat(); @SuppressWarnings("unused") List list = new ArrayList(); @SuppressWarnings("unused") int i =10; // System.out.println(i); } } @MyAnnotation(value = "Peter") class Student extends Person { @Override public void walk() { System.out.println("学生走路"); } @Override public void eat() { System.out.println("学生吃饭"); } } @Deprecated class Person { String name; int age; public Person() { } @MyAnnotation(value = "Peter") public Person(String name, int age) { this.name = name; this.age = age; } @MyAnnotation(value = "Peter") public void walk() { System.out.println("走路"); } @Deprecated public void eat() { System.out.println("吃饭"); } }
结果:
学生走路
学生吃饭
MyAnnotation 代码示例:
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.LOCAL_VARIABLE; //自定义注解 @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default "hello"; }