注解的使用方式(运行期)

2021-05-06  本文已影响0人  老林_

代码结构


image.png

定义一个注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BeforeDoing {
    String target();
    String words() default "Nothing to say.";
}

注解的使用

/**
 * 去学校之前处理注解
 */
public class Student {
    private Playing play1=new Playing();
    public Student() {

    }

    @BeforeDoing(target = "play1",words = "拜拜")
    public void goToSchool() throws InvocationTargetException,
            NoSuchMethodException, IllegalAccessException, NoSuchFieldException {
        AnnotationUtils.stuTest(this);
    }

}

注解的处理

public class AnnotationUtils {
    public static void stuTest(Object o) throws NoSuchFieldException, IllegalAccessException,
            InvocationTargetException, NoSuchMethodException {
        Class<?> cls = o.getClass();
        for (Method m:
             cls.getMethods()) {
            boolean annotationPresent = m.isAnnotationPresent(BeforeDoing.class);
            if(annotationPresent){
                BeforeDoing annotation = m.getAnnotation(BeforeDoing.class);
                String target = annotation.target();
                String words = annotation.words();
                if(target!=null){
                    Field field = o.getClass().getDeclaredField(target);
                    field.setAccessible(true);
                    //得到这个字段对象
                    Object o1 = field.get(o);
                    //得到some方法,形参一定要的,不然找不到方法
                    Method words1 = o1.getClass().getMethod("some",String.class);
                    words1.setAccessible(true);
                    words1.invoke(o1,words);
                }
            }
        }
    }
}

辅助类

public class Playing {
    public void some(String s){
        System.out.println(s);
    }
}

在Main中进行测试

public class Main {
    public static void main(String[] args) {
        Student student=new Student();
        try {
            student.goToSchool();
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

编译

javac -encoding utf-8 com/ly/annotation/test2/Main.java

编译结果


image.png

运行

java com.ly.annotation.test2.Main

运行结果


image.png
上一篇 下一篇

猜你喜欢

热点阅读