我已经定义了以下java Annotation
@Target({ElementType.METHOD, ElementType.PARAMETER, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "";
}
Run Code Online (Sandbox Code Playgroud)
我定义了以下scala案例类:
@Prefer("xyz")
case class TestAnno(arg1 : String, @Prefer("abc") agr2 : String)
Run Code Online (Sandbox Code Playgroud)
我能够使用反射看到在案例类级别定义的注释,但是我无法访问arg2为案例类成员定义的注释TestAnno.反编译代码我发现变量声明或它的scala访问器似乎都没有注释.只有构造函数定义和copy方法似乎保留了case类声明中定义的参数的注释.
是否有其他方法可以强制scala编译器为case类中声明的字段生成注释,或者我必须读取构造函数并使用诸如ASM ByteCode Library或ParaNamer之类的库来查找哪些参数具有哪些注释?需要一个主要适用于Scala案例类的解决方案.
我正在尝试实现这里描述的隐式物化器:http://docs.scala-lang.org/overviews/macros/implicits.html
我决定创建一个宏,用于将case类转换为String使用quasiquotes进行原型设计.例如:
case class User(id: String, name: String)
val foo = User("testid", "foo")
Run Code Online (Sandbox Code Playgroud)
foo应该导致转换为文本"testid foo",反之亦然.
这是我创建的简单特征及其伴随对象:
trait TextConvertible[T] {
def convertTo(obj: T): String
def convertFrom(text: String): T
}
object TextConvertible {
import language.experimental.macros
import QuasiTest.materializeTextConvertible_impl
implicit def materializeTextConvertible[T]: TextConvertible[T] = macro materializeTextConvertible_impl[T]
}
Run Code Online (Sandbox Code Playgroud)
这是宏:
object QuasiTest {
import reflect.macros._
def materializeTextConvertible_impl[T: c.WeakTypeTag](c: Context): c.Expr[TextConvertible[T]] = {
import c.universe._
val tpe = weakTypeOf[T]
val fields = tpe.declarations.collect {
case field if field.isMethod && …Run Code Online (Sandbox Code Playgroud)