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

     

  • 相关阅读:
    项目架构工具选择
    idea 引入本地jar包
    java 二维/三维/多维数组
    Windows 远程连接
    SQL SERVER 本地同步数据到远程数据服务器
    利用sp_addlinkedserver实现远程数据库链接
    ORACLE 手动添加时间分区
    ORACLE 时间段
    shiro异常简述
    kvm虚拟机克隆
  • 原文地址:https://www.cnblogs.com/clarino/p/14460894.html
Copyright © 2011-2022 走看看