zoukankan      html  css  js  c++  java
  • 【Java基础】注解


    判断指定注解是否存在: boolean annotationPresent = method.isAnnotationPresent(MyAnnotation.class);


    1.  自定义注解:MyAnnotation
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
        public @interface MyAnnotation {    
    }
    2、使用:MyAnnotationDemo 
    @Deprecated
    public class MyAnnotationDemo {
        @MyAnnotation
        public void print()
        {
            System.out.println("call print()");
        }
    }

        3. 测试类

    public class MyAnnotationDemoTest {
        public static void main(String[] args) throws Exception {
            Class<?> clazz = Class.forName("com.demo.annotation.MyAnnotationDemo");
            printClassInfo(clazz);
    Method[] methods
    = clazz.getMethods(); printMethodInfo(clazz, methods); } private static void printClassInfo(Class<?> clazz) { for (Annotation annotation : clazz.getAnnotations()) { System.out.println("class annotation name: " + annotation.toString()); } } private static void printMethodInfo(Class<?> clazz, Method[] methods) throws Exception { for (Method method : methods) { // 判断方法是否有指定的注解信息 boolean annotationPresent = method.isAnnotationPresent(MyAnnotation.class); if (annotationPresent) { System.out.println(method.getName());

    // 反射方式调用当前方法 method.invoke(clazz.getConstructor(
    null).newInstance(null), null); method.invoke(clazz.newInstance(), null); for (Annotation annotation : method.getAnnotations()) { System.out.println("method annotation: " + annotation.toString()); } } } } }

        4. 测试结果:

    
    class annotation name: @java.lang.Deprecated()
    
    print
    call print()
    call print()
    method annotation: @com.demo.annotation.MyAnnotation()

     

  • 相关阅读:
    线程循环的故事
    代码质量
    代码质量控制之异常控制
    面对象静态结构描述方法
    解决maven下载依赖包,pom文件错误问题
    Spring学习笔记
    java编程命名规范
    powershell使用
    vert.x中future的简单使用
    idea调整import包的顺序
  • 原文地址:https://www.cnblogs.com/clarino/p/14460894.html
Copyright © 2011-2022 走看看