所以我想列出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列表总是空... fields
已str
上市但没有注释。
我错过了什么?
列出注释的代码是从以下答案: How to list all fields with a custom annotation using Scala's reflection at runtime?
您可能会仅在构造函数params上注释。我的答案[这里](https://stackoverflow.com/questions/41176273/get-case-class-annotations-with-reflection/41197711)可能会有所帮助。 –