本次我们先来看JDK提供的三个内置注解:@Override、@Deprecated、@SuppressWarnings
package com.bit.annotation;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* Description:
* User: wang
* Date: 2019-05-20
* Time: 13:56
**/
public class Member implements Serializable {
@Override
@Deprecated
public String toString() {
return super.toString();
}
}
ackage com.bit.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created with IntelliJ IDEA.
* Description:
* User: wang
* Date: 2019-05-20
* Time: 14:09
**/
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE})
public @interface MyAnnotation{
String name() default"无名";
int age() default 18;
}
package com.bit.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* Created with IntelliJ IDEA.
* Description:
* User: wang
* Date: 2019-05-20
* Time: 13:58
**/
public class TestMember {
public static void code1() {
Class cls = Member.class;
Annotation[] annotations = cls.getAnnotations();
for(Annotation annotation:annotations){
System.out.println(annotation);
}
// try{
// Method method = cls.getMethod("toString");
// Annotation[] annotations = method.getAnnotation();
// for (Annotation annotation:annotations){
// System.out.println(annotation);
//
// }
//
}
public static void main(String[] args) {
Class cls = Member.class;
MyAnnotation myAnnotation = (MyAnnotation) cls.getDeclaredAnnotation(MyAnnotation.class);
System.out.println(myAnnotation);
int age = myAnnotation.age();
String name = myAnnotation.name();
System.out.println(name +" " + age);
}
}