gpt4 book ai didi

java - 如何创建现有注释的快捷方式?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:20 24 4
gpt4 key购买 nike

在我的代码中,我多次使用以下注释:

@JsonSerialize(using = classOf[CustomColorRGBASerializer])

为了让我的代码简短并且DRY ,我想为此创建一个快捷方式,例如:

class JsonSerializeARGB
extends @JsonSerialize(using = classOf[CustomColorRGBASerializer])

然后我可以将其用作新的 @JsonSerializeARGB 注释

我可以使用注释,但我不知道如何定义它们,因此我的尝试当然看起来很幼稚而且显然是不正确的,但我希望它能表达意思。

我已阅读 How do you define an @interface in Scala?How to create annotations and get them in scala ,但它们对我帮助不大,因为我不想创建全新的注释,而是“子类化”现有注释。这能做到吗?

如果没有Scala的解决方案,Java能不能做这样的事情? (无论如何,我正在使用的 Jackson annotations 都是用 Java 定义的)。

最佳答案

恐怕有no way to subtype annotation with Java (和 Scala)语言机制。我认为唯一的解决方案是制作 Scala macro with the annotation .

Macro annotations可用于 Macro Paradise plugin对于 Scala 编译器。希望它们会包含在 Scala 2.13 中。要为 Macro Paradise 配置 SBT,您可能需要关注 this question .还有一个useful example项目利用宏观天堂。

我相信这可以做得更好(尤其是 DefDef 匹配),但是类似于这个的宏应该可以解决您的问题:

import scala.reflect.macros._
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros

class JsonSerializeARGB extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro JsonSerializeARGBMacroImpl.impl
}

object JsonSerializeARGBMacroImpl extends JsonSerializeARGBMacro

class JsonSerializeARGBMacro {
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._

def modifiedDef(d: DefDef) = {
val (mods, name, tparams, paramss, tpt, body) = try {
val q"$mods def $name[..$tparams](...$paramss): $tpt = $body" = d
(mods, name, tparams, paramss, tpt, body)
} catch {
case _: MatchError => c.abort(c.enclosingPosition, "Failed to match...")
}

//TODO there is a problem with modifiers
c.Expr(q"""
@JsonSerialize(using = classOf[CustomColorRGBASerializer])
def $name[..$tparams](...$paramss): $tpt = $body
""")
}

annottees.map(_.tree) match {
case (d: DefDef) :: Nil => modifiedDef(d)
case _ => c.abort(c.enclosingPosition, "Invalid annottee.")
}
}
}

关于java - 如何创建现有注释的快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28173994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com