2017-08-24 21 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

相關問題