动态代理,无需在scala中明确指定类型
是否可能有一个方法接受任意实例并返回与原始参数具有相同类型的java.reflection.Proxy或类似对象 我想应该是这样的:动态代理,无需在scala中明确指定类型,scala,dynamic,proxy,Scala,Dynamic,Proxy,是否可能有一个方法接受任意实例并返回与原始参数具有相同类型的java.reflection.Proxy或类似对象 我想应该是这样的: def createProxy[S](model: S)(implicit manifest: Manifest[S]): S = {...} val sessionSvc = createProxy(new SessionSvcMongo, classOf[SessionSvc]) 还是这个 def createProxy[S, T<:S](model
def createProxy[S](model: S)(implicit manifest: Manifest[S]): S = {...}
val sessionSvc = createProxy(new SessionSvcMongo, classOf[SessionSvc])
还是这个
def createProxy[S, T<:S](model: S)(implicit manifest: Manifest[S]): T = {...}
def createProxy[S,T我认为应该使用以下方法。请注意,它不能返回S,因为它可能不是接口
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:_*)
}
})
}
在需要使用单个接口代理对象的情况下,可以执行以下操作(基于Hiram Chirino回答):
并且有一个接口SessionSvc
这样使用它:
def createProxy[S](model: S)(implicit manifest: Manifest[S]): S = {...}
val sessionSvc = createProxy(new SessionSvcMongo, classOf[SessionSvc])
通过这种方式,我成功地在基于cake模式的代码库中引入了相当轻松的AOP。结果类型是Object,因此它无法解决我的问题。看起来我不能得到我想要的,所以我接受这个答案。虽然有点旧,但…代理只能转换到接口,而不能转换到具体的类