Java注释不起作用 [英] Java Annotations not working

查看:44
本文介绍了Java注释不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Java 注释,但似乎无法让我的代码识别出存在的注释.我究竟做错了什么?

I'm trying to use Java annotations, but can't seem to get my code to recognize that one exists. What am I doing wrong?

  import java.lang.reflect.*;
  import java.lang.annotation.*;

  @interface MyAnnotation{}


  public class FooTest
  { 
    @MyAnnotation
    public void doFoo()
    {       
    }

    public static void main(String[] args) throws Exception
    {               
        Method method = FooTest.class.getMethod( "doFoo" );

        Annotation[] annotations = method.getAnnotations();
        for( Annotation annotation : method.getAnnotations() )
            System.out.println( "Annotation: " + annotation  );

    }
  }

推荐答案

您需要使用注解界面上的@Retention 注解将注解指定为运行时注解.

You need to specify the annotation as being a Runtime annotation using the @Retention annotation on the annotation interface.

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{}

这篇关于Java注释不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆