自定义注解-例子

1.注解类

package Annotations;

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 ClassMethodAnnotation {

    Class c();
    String method();
}

2.注解使用

package Annotations;

public class test {

    @ClassMethodAnnotation(c=test.class,method="test1")
    public void test(){
        System.out.println("===test方法执行了!!!!!");
    }
    
    
    public void test1(){
        System.out.println("test1方法执行了!!!!!");
    }
}

3.测试

package Annotations;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotationMainTest {

    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException {
        ClassMethodAnnotationTest();
    }

    
    public static void ClassMethodAnnotationTest() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException{
        Class testClass = test.class;
        Method[] method = testClass.getMethods();
        for (Method method2 : method) {
            if(method2.isAnnotationPresent(ClassMethodAnnotation.class)){
                ClassMethodAnnotation annotation = method2.getAnnotation(ClassMethodAnnotation.class);
                Class annClass = annotation.c();
                String annMethod = annotation.method();
                Method[] anmethod = annClass.getMethods();
                for (Method method3 : anmethod) {
                    if(method3.getName().equals(annMethod)){
                        System.out.println("带注解的方法为:"+method2.getName());
                        method3.invoke(annClass.newInstance(), null);
                    }
                }
            }
        }
    }
}

执行结果:

原文地址:https://www.cnblogs.com/chinazhou-wang/p/11573380.html