如何在运行时访问在案例类字段上定义的注释 [英] How to access Annotation defined on case class field at Runtime

查看:95
本文介绍了如何在运行时访问在案例类字段上定义的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下Java注释

I've the following java Annotation defined

   @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.FIELD})
   @Retention(RetentionPolicy.RUNTIME)
   public @interface MyAnnotation { 
     String value() default "";
   }

我定义了以下scala case类:

And I've the following scala case class defined:

@Prefer("xyz")
case class TestAnno(arg1 : String, @Prefer("abc") agr2 : String)

我可以使用反射看到在案例类级别定义的注释,但是我无法访问为案例类TestAnnoarg2成员定义的注释.反编译代码,我发现变量声明或它的scala访问器似乎都没有注释.只有构造函数定义和copy方法似乎保留了在case类声明中定义的参数注释.

I'm able see the annotation defined at case class level using reflection but I'm not able to access the annotation defined for arg2 member of case class TestAnno. De-compiling the code I see that neither the variable declaration or it's scala accessor seem to have the annotation. Only the constructor definition and copy method seem to retain the annotation for the parameters as defined in case class declaration.

是否有其他方法可以强制scala编译器为case类中声明的字段生成注释,或者我必须阅读构造函数并使用诸如 ParaNamer 来查找哪些参数具有哪些注释?需要一种主要适用于Scala案例类的解决方案.

Is there some other way to force the scala compiler to generate annotations for the fields declared in case class or I have to read the constructor and use a library such as ASM ByteCode Library or ParaNamer to find which parameters have which annotations? Need a solution which will work primarily for Scala case classes.

推荐答案

您只需要执行以下操作:

You just need to do the following :

case class TestAnno(arg1 : String, @(Prefer @field)("abc") agr2 : String)

此处的更多信息 http://www.scala- lang.org/api/current/#scala.annotation.meta.package

这篇关于如何在运行时访问在案例类字段上定义的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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