Java注解不工作 [英] Java Annotations not working

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

问题描述

我试图用Java注解,但似乎无法让我的code认识到存在的话。
我究竟做错了什么?

 进口java.lang.reflect中的*。
  导入java.lang.annotation中*。  @interface MyAnnotation {}
  公共类FooTest
  {
    @MyAnnotation
    公共无效doFoo()
    {
    }    公共静态无效的主要(字串[] args)抛出异常
    {
    方法方法= FooTest.class.getMethod(doFoo);    注释[] =注释method.getAnnotations();
    对于(译注注解:method.getAnnotations())
    的System.out.println(李善注:+注解);    }
  }


解决方案

您需要指定注释作为是使用注释界面上的@Retention标注一个运行时的注释。

即。

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

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

    }
  }

解决方案

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

i.e.

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

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

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