Scala 的反射 API [英] Reflection API for Scala

查看:31
本文介绍了Scala 的反射 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道 Scala 的全功能反射 API 的状态?

Does anyone know the status of a fully-featured reflection API for Scala?

我知道您可以使用 Java 的反射 API 来做一些简单的事情,但这对 Scala 的语言特性来说效果不佳.我发现了一篇 有趣的文章 描述了一个实验性的 Scala 镜像 API,但就我知道这仍然是实验性的.我还发现提到了 ScalaSigParser,但这似乎是相当低级的.

I know that you can use Java's reflection API to do simple things but this does not work well with Scala's language features. I found an interesting article describing an experimental Scala Mirroring API but as far as I know this is still experimental. I've also found mention of a ScalaSigParser but this seems to be pretty low level.

这更像是一种好奇心,因为我目前只是在玩 Scala.我认为这个问题的答案可能对其他对 Scala 感兴趣的人也有用.

This is more of a curiosity than anything else as I am currently just playing around with Scala. I thought that the answer to this question might also be useful to others interested in Scala.

推荐答案

JavaBean 样式模式的不可变替换"可以通过命名参数和可选的 @BeanProperty 注释来表达:

The "immutable replacement for the JavaBean style pattern" can be expressed named parameters and optionally the @BeanProperty annotation:

import reflect._
case class A(@BeanProperty val x: String, @BeanProperty val y : Int)

A(x = "s", y = 3)
A(y = 3, x = "s")

添加方法(更准确地说:定义新接口)只有在客户端知道新方法并且可以针对接口进行编译时才在静态类型语言中有意义.使用结构化类型,客户可以定义他们希望出现在对象中的方法.Scala 编译器会将结构类型转换为可能在运行时失败的反射代码.

Adding methods (more precise: defining a new interface) makes only sense in a statically typed language if the client knowns about the new methods and can compile against the interface. With structural typing clients can define methods they expect to be present in an object. The Scala compiler will transform the structural type into reflection code which may fail at runtime.

type T = {def go(x : Int): Int }
def y(any : Any) = any.asInstanceOf[T].go(2)

class A{
  def go(x : Int) = x + 1
}
y(new A())
y(new {}) //this will fail

您可以使用 口译 动态.Interpret 方法将 Scala 代码转换为字节码.

You can define new classes or traits with the interpreter on the fly. The Interpret method transforms Scala code to byte code.

您已经提到了 ScalaSigParser,它并不容易使用.

You've already mentioned the ScalaSigParser which is not exactly easy to work with.

我认为您喜欢的其他功能尚不存在.

I think the rest of features you like are not there yet.

这篇关于Scala 的反射 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆