需求:定义若干个方法,只有加了MyTest注解,就可以在启动时被执行
分析:
定义一个自定义注解MyTest,只能注解方法,存活范围是一直都在
定义若干个方法,只要有@MyTest注解的方法就能在启动时被触发,没有这个注解的方法不能执行
-
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface MyTest {
-
- }
主函数
-
-
- import java.lang.reflect.Method;
-
- public class Test {
- @MyTest
- public void test1() {
- System.out.println("----txst1---");
- }
- public void text2() {
- System.out.println("----txst3---");
- }
- @MyTest
- public void test3() {
- System.out.println("----txst3---");
- }
-
-
-
- public static void main(String[] args) throws Exception{
- // 被MyTest标记的方法才可以被执行
- Test T=new Test();//创建一个测试对象,一会调用用
- Class c=Test.class; //获取类对象
- Method[] arr=c.getDeclaredMethods();//获取此类中全部方法
- for (Method method : arr) {//开始遍历
- //判断是否存在@MyTest注解
- if(method.isAnnotationPresent(MyTest.class)) {
- //如果存在就执行
- method.invoke(T);
- }
-
- }
-
- }
-
- }