package com.guaji.exer;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/* 如何自定义注解:
* 1. 参照@SuppressWarnings定义
2. 注解声明为:@interface
3. 内部定义成员,通常使用value表示
4. 可以指定成员的默认值,使用default定义
5. 如果自定义注解没有成员,表明是一个标识作用 如果注解有成员,在使用注解是,需要指明成员的值
四种元注解:
元注解:对现有的注解进行解释说明的注解
Retention:指定所修饰的Annotation的生命周期,SOURCE\CLASS(默认行为)\RUNTIME只有声明为RUNTIM生命周期的注解,才能通过反射获取
Target:用于指定被修饰的Annotation能用于修饰哪些程序元素
Documented:表示所修饰的注解在Javadoc解析时,保留下来
Inherited:被它修饰的Annotation将具有继承性
*/
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
String value() default "hello";
}
package com.guaji.exer;
import java.lang.annotation.Annotation;
import java.sql.Date;
import org.junit.Test;
/* 在编译时进行格式检查(JDK内置的三个基本注解)
* 1. @Override限定重写父类方法,该注解只能用于方法
2. @Deprecated:用于表示所修饰的元素(类,方法等)已过时
3. @SuppressWarnings:抑制编译器警告
* */
@MyAnnotation("helloWorld")
class Person{
private String name;
private String sex;
public Person(){}
public Person(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public void show(){
System.out.println("姓名:"+name+"性别:"+sex);
}
}
class Student extends Person{
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
}
}
public class AnnotationExer {
@Test
public void Test1(){
Class clazz=Student.class;
Annotation[] annotations = clazz.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println(annotations[i]);
}
}
public static void main(String[] args) {
Date date = new Date(213213213L);
/* @Deprecated
public Date(int year, int month, int day) {
super(year, month, day);
}*/
java.util.Date date2 = new java.util.Date(3213L);
}
}