package com.example.test;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 注解的定义和使用
*/
public class AnnotationDefineAndUse {
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
public int hello() default 0;
}
@Target({ElementType.TYPE, ElementType.METHOD})//作用范围为 类、方法
@Retention(RetentionPolicy.RUNTIME) //运行时生效
@Documented
public @interface MyAnnotation1 {
}
/**
* 测试注解
*/
public static void main(String[] args) {
Test t = new Test();
//使用遍历的方式获取
/*Annotation[] an= t.getClass().getAnnotations();
for(Annotation a:an){
System.out.println(a.annotationType().getName());
}*/
if (t.getClass().isAnnotationPresent(MyAnnotation1.class)) {//如果类的注解存在
MyAnnotation1 my1 = t.getClass().getAnnotation(MyAnnotation1.class);
System.out.println(my1.annotationType().getName());
System.out.println("你得到了类的注解");
}
try {
Method method1 = t.getClass().getMethod("test1", new Class[]{});
Method method2 = t.getClass().getMethod("test2", new Class[]{});
Method method3 = t.getClass().getMethod("test3", new Class[]{});
try {
//方法的调用
method1.invoke(t, null);
System.out.println(method1.getModifiers());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//如果方法的注解存在
if (method1.isAnnotationPresent(MyAnnotation1.class)) {
MyAnnotation1 my1 = method1.getAnnotation(MyAnnotation1.class);
System.out.println(my1.annotationType().getName());
System.out.println("你得到了方法test1上的MyAnnotation1注解");
}
if (method2.isAnnotationPresent(MyAnnotation2.class)) {
MyAnnotation2 my2 = method2.getAnnotation(MyAnnotation2.class);
System.out.println(my2.hello());//得到注解默认值
System.out.println("你得到了方法test2上的MyAnnotation2注解");
}
if (method3.isAnnotationPresent(MyAnnotation2.class)) {
MyAnnotation2 my3 = method3.getAnnotation(MyAnnotation2.class);
System.out.println(my3.hello());//得到赋予的值
System.out.println("你得到了方法test3上的MyAnnotation2注解");
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
@MyAnotationTest.MyAnnotation1
class Test {
@MyAnotationTest.MyAnnotation1
public void test1() {
System.out.println("你使用了MyAnnotation1");
}
@MyAnotationTest.MyAnnotation2
public void test2() {
System.out.println("你使用了MyAnnotation2默认值");
}
@MyAnotationTest.MyAnnotation2(hello = 3)
public void test3() {
System.out.println("你使用了MyAnnotation2并为其赋值");
}
}
注解的定义和使用
最新推荐文章于 2021-12-19 19:30:03 发布