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()

     

  • 相关阅读:
    19年下半年读书清单一览
    2019-2020:时间戳
    全链路压测资料汇总——业内大厂解决方案
    个人公众号开通啦
    windows 10环境下安装Tensorflow-gpu
    如何判断安卓模拟器的型号(品牌)
    socket.io的websocket示例
    Node + Selenium使用小结
    基于SOUI开发一个简单的小工具
    国际化之Android设备支持的语种
  • 原文地址:https://www.cnblogs.com/clarino/p/14460894.html
Copyright © 2011-2022 走看看