scala - 动态代理,无需在 scala 中显式指定类型

标签 scala dynamic proxy

是否有可能有一个方法,它接受任意实例并返回 java.reflection.Proxy 或与原始参数具有相同类型的类似对象?

我想它应该看起来像这样:

def createProxy[S](model: S)(implicit manifest: Manifest[S]): S = {...}

或者这个

def createProxy[S, T<:S](model: S)(implicit manifest: Manifest[S]): T = {...}

其中 T 是 S 的子类型,它是由所有已实现的接口(interface)组合而成的,因为我似乎无法代理实际的类,而只能代理接口(interface)。

最佳答案

我认为以下应该可以解决问题。请注意,它无法返回 S,因为 S 可能不是接口(interface)。

import java.lang.reflect._

def createProxy[S](model: S)(implicit manifest: Manifest[S]) = {
  val clazz = manifest.erasure 
  Proxy.newProxyInstance(clazz.getClassLoader, clazz.getInterfaces, new InvocationHandler() {
    def invoke(proxy:Object, method:Method, args:scala.Array[Object]) = {
      method.invoke(model, args:_*)
    }
  })
}

关于scala - 动态代理,无需在 scala 中显式指定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3900904/

相关文章:

scala - 设置 Cassandra 表扫描上的 Spark 任务数

c - 需要解释此代码(算法)

c# - 每个都有一个动态列表?

Python:Python 中的互联网内容适配协议(protocol) (ICAP) 客户端实现

docker - 如何配置 docker 容器代理?

scala - 对 DStream 进行排序并取 topN

scala - 如何用猫将 `NonEmptyList[Either[Error, User]]` 转换为 `Either[Error, NonEmptyList[User]]`?

c - 不加载 c 库的 perl 语法检查

java - OSX 上 JVM 的 Zombie http.proxyHost 设置

scala - SBT 中使用的 `addCommandAlias` 方法中的第一个分号是什么?