1.定义注解
package com.wxd.study1.study.study20200310;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyFirstAnnotation {
String name() default "wxd";
int age() default 18;
}
2.将注解放在类或者方法上
package com.wxd.study1.study.study20200310;
@MyFirstAnnotation(name = "wxd类注释",age = 21)
public class MethodClass {
@MyFirstAnnotation(name = "wxd方法注释")
public void test1(){
System.out.println(123);
}
@MyFirstAnnotation(name = "ggg",age = 22)
public void ttt2(){
System.out.println(123312312);
}
}
3.在main方法中测试
package com.wxd.study1.study.study20200310;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
Class aClass = MethodClass.class;
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
Method[] methods = aClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
System.out.println(method.getName());
}
Annotation annotation = aClass.getAnnotation(MyFirstAnnotation.class);
System.out.println("---------"+annotation);
System.out.println("---------------------------------------#########################");
MyFirstAnnotation annotation1 = MethodClass.class.getAnnotation(MyFirstAnnotation.class);
System.out.println(annotation1.name());
System.out.println(annotation1.age());
Method[] declaredMethods = MethodClass.class.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
System.out.println(declaredMethod.getAnnotation(MyFirstAnnotation.class).age());
System.out.println(declaredMethod.getAnnotation(MyFirstAnnotation.class).name());
System.out.println(declaredMethod.getName());
}
}
}
4:输出
@com.wxd.study1.study.study20200310.MyFirstAnnotation(name=wxd类注释, age=21)
public void com.wxd.study1.study.study20200310.MethodClass.ttt2()
ttt2
public void com.wxd.study1.study.study20200310.MethodClass.test1()
test1
---------@com.wxd.study1.study.study20200310.MyFirstAnnotation(name=wxd类注释, age=21)
---------------------------------------#########################
wxd类注释
21
22
ggg
ttt2
18
wxd方法注释
test1
注意: class.getAnnotation(Class<A> annotationClass)方法中,前面为使用的注解的类class,括号中的参数为注解的class
如上就是MethodClass.class.getAnnotation(MyFirstAnnotation.class);
MethodClass为使用了注解的类,
MyFirstAnnotation为创建的注解类。否则能方法获取的Annotation对象为null