有没有Scala功能允许您调用名称存储在字符串中的方法? [英] Is there any Scala feature that allows you to call a method whose name is stored in a string?

查看:101
本文介绍了有没有Scala功能允许您调用名称存储在字符串中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个包含方法名称的字符串,支持该方法的对象和一些参数,是否有一些语言功能允许您动态调用?



类似Ruby的发送参数。

解决方案

您可以在Java中进行反思:

  class A {
def cat(s1:String,s2:String)= s1 ++ s2
}
val a = new A
val hi =Hello
val all =世界
val方法= a.getClass.getMethod(cat,hi.getClass,all.getClass)
method.invoke(a,hi,all)

如果您希望在Scala中轻松实现,您可以为您做一个类,另外还有一个隐含的转换:

 案例类调用者[T>:Null<:AnyRef](klass:T){
def call(methodName:String, args:AnyRef *):AnyRef = {
def argtypes = args.map(_。getClass)
def method = klass.getClass.getMethod(methodName,argtypes:_ *)
方法。 invoke(klass,args:_ *)
}
}
implicit def anyref2callable [T>:Null<:AnyRef](klass:T):Caller [T] = new Caller )
a call(ca t,那里)

做这种事情会转换编译时错误进入运行时错误,它基本上规避了类型系统),所以谨慎使用。



(编辑:看到在上面的链接中使用NameTransformer - 添加,如果你尝试使用运算符。)


Assuming you have a string containing the name of a method, an object that supports that method and some arguments, is there some language feature that allows you to call that dynamically?

Kind of like Ruby's send parameter.

解决方案

You can do this with reflection in Java:

class A {
  def cat(s1: String, s2: String) = s1 + " " + s2
}
val a = new A
val hi = "Hello"
val all = "World"
val method = a.getClass.getMethod("cat",hi.getClass,all.getClass)
method.invoke(a,hi,all)

And if you want it to be easy in Scala you can make a class that does this for you, plus an implicit for conversion:

case class Caller[T>:Null<:AnyRef](klass:T) {
  def call(methodName:String,args:AnyRef*):AnyRef = {
    def argtypes = args.map(_.getClass)
    def method = klass.getClass.getMethod(methodName, argtypes: _*)
    method.invoke(klass,args: _*)
  }
}
implicit def anyref2callable[T>:Null<:AnyRef](klass:T):Caller[T] = new Caller(klass)
a call ("cat","Hi","there")

Doing this sort of thing converts compile-time errors into runtime errors, however (i.e. it essentially circumvents the type system), so use with caution.

(Edit: and see the use of NameTransformer in the link above--adding that will help if you try to use operators.)

这篇关于有没有Scala功能允许您调用名称存储在字符串中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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