2017-08-24 24 views
0

所以我想列出Scala案例类中具有特定注释的字段,并且我无法使其工作......让我们来看看前来代码马上如何在Scala案例类的字段成员上列出注释(自定义java和其他)

的情况下类(这是它的简化版本,雷扩展了另一个类,也嵌套在我的测试类,我用它仅用于单元测试):

case class Foo(@Unique var str: String) {} 

Java定制注释:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.FIELD, ElementType.PARAMETER}) 
public @interface Unique {} 

而我的等级(再次简化)这里我试图做一些东西与域标记为唯一

class SomeClass[T] (implicit typeTag: TypeTag[T]) { 
    val fields: Iterable[universe.TermSymbol] = typeOf(typeTag).members.collect { case s: TermSymbol => s }. 
               filter(s => s.isVal || s.isVar) 
    val list = fields.flatMap(f => f.annotations.find(_.tpe =:= TypeOf[Unique]).((f, _))).toList 
} 

但在代码的最后和平VAL列表总是空... fieldsstr上市但没有注释。

我错过了什么?

列出注释的代码是从以下答案: How to list all fields with a custom annotation using Scala's reflection at runtime?

+0

您可能会仅在构造函数params上注释。我的答案[这里](https://stackoverflow.com/questions/41176273/get-case-class-annotations-with-reflection/41197711)可能会有所帮助。 –

回答

1

似乎基准柱是斯卡拉2.10是旧的,而不是与最新的Scala版本兼容。

有一个例子,如何得到指定注释类型

def listProperties[T: TypeTag]: List[universe.Annotation] = { 
    typeOf[T].typeSymbol.asClass 
     .asClass 
     .primaryConstructor 
     .typeSignature 
     .paramLists.flatten.flatMap(_.annotations) 
    } 

    val annotations = listProperties[Foo].filter(_.tree.tpe =:= typeOf[Unique]) 
    println(annotations) 

并有办法让注释的字段值:

case class Foo(@Unique(field = "bar") val str: String) {} 
    import scala.reflect.runtime.currentMirror 
    import scala.tools.reflect.ToolBox 

    val tb = currentMirror.mkToolBox() 
    val result = tb.eval(tb.untypecheck(head.tree)).asInstanceOf[Unique] 

,需要调出你的注释类为实现通过使用的Java风格,在斯卡拉也许你想使用StaticAnnotation来创建Annotation,如:

class Unique extends StaticAnnotation 
+0

谢谢,您的解决方案按预期工作。 :) – Jeep87c

相关问题