zoukankan      html  css  js  c++  java
  • 自定义注解-例子

    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);
                        }
                    }
                }
            }
        }
    }

    执行结果:

  • 相关阅读:
    java环境配置为1.7jdk为什么cmd java -version查看版本是1.8
    bulid path 引 jar包 步骤
    eclipse 报错
    PLSQL使用技巧
    Oracle sqlplus不是内部或外部命令
    SVN 插件安装到Myeclipse10 上(经典)
    socket学习
    Eclipse 配置 插件svn 包步骤
    如何在Eclipse中使用SVN(经典)
    linux 下搭建LAMP
  • 原文地址:https://www.cnblogs.com/chinazhou-wang/p/11573380.html
Copyright © 2011-2022 走看看