【问题标题】:Annotating case class parameters注释案例类参数
【发布时间】:2018-07-23 19:28:00
【问题描述】:

我正在尝试注释案例类的参数。

this question来看,和 从这个scaladoc 看来,我正在做的事情应该可以工作,但由于某种原因它没有:

class Foo extends java.lang.annotation.Annotation { def annotationType = getClass }
case class Bar(@Foo @getter bar: String) 
classOf[Bar].getDeclaredMethods.map(_.getDeclaredAnnotations.length)

res66: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

有什么想法吗?

【问题讨论】:

    标签: scala annotations case-class


    【解决方案1】:

    用 Java 编写注释。 @getter 也应该用作 meta-注解。

    Foo.java

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Foo {
    }
    

    Bar.scala

    case class Bar(@(Foo @getter) bar: String)
    

    然后

    classOf[Bar].getDeclaredMethods.map(_.getDeclaredAnnotations.length)
    // Array(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    

    Why annotations written in Scala are not accessible at runtime?

    【讨论】:

    • 我知道怎么用java写,谢谢。我的问题是关于 scala。
    • 我的回答是关于 Scala。您应该用 Java 编写注解并在 Scala 中使用它。
    • 太糟糕了... :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多