使用 Scala 搜索方法中的注释
以下代码无法编译(Output
不是 java.reflect.annotation.Annotation
类型):
class Output(val name : String) extends Annotation
class Block {
def outputs {
for {
method <- this.getClass.getMethods
val a = method.getAnnotation(classOf[Output])
if a != null
} {
println(a.name)
}
}
}
class Arithmetic[T: Numeric](val A: Connector[T], val B: Connector[T]) extends Block {
@Output("Sum") def Sum = new Connector({ A.Value + B.Value })
@Output("Difference") def Diff = new Connector({ A.Value - B.Value })
@Output("Multiply") def Mul = new Connector({ A.Value * B.Value })
}
有没有办法实现带注释的成员的运行时反射?
The following code fails to compile (Output
is not of type java.reflect.annotation.Annotation
):
class Output(val name : String) extends Annotation
class Block {
def outputs {
for {
method <- this.getClass.getMethods
val a = method.getAnnotation(classOf[Output])
if a != null
} {
println(a.name)
}
}
}
class Arithmetic[T: Numeric](val A: Connector[T], val B: Connector[T]) extends Block {
@Output("Sum") def Sum = new Connector({ A.Value + B.Value })
@Output("Difference") def Diff = new Connector({ A.Value - B.Value })
@Output("Multiply") def Mul = new Connector({ A.Value * B.Value })
}
Is there any way to achieve runtime reflection on the annotated members?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
Block.getClass
应该是classOf[Block]
。getClass
适用于实例。(java 等效项:
x.getClass
<=>x.getClass()
.classOf[X]
<=>X.class
。x.getClass
x.GetType()
。 > <=>typeof(X)
)Your
Block.getClass
should beclassOf[Block]
.getClass
works on instances.(java equivalent:
x.getClass
<=>x.getClass()
.classOf[X]
<=>X.class
. C# equivalent:x.getClass
<=>x.GetType()
.classOf[X]
<=>typeof(X)
)似乎在 Scala 中还没有办法实现这一点,因此我们应该求助于使用 Java 类:
It seems there is no way to achieve this in Scala (yet), and thus we should resort to using a Java class as such: