scala - 从字符串中获取类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9268873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scala - get class from a string
提问by Todd M
From Scala, I'm using a Java library that expects a class argument. Example:
在 Scala 中,我使用的是一个需要类参数的 Java 库。例子:
def service: OAuthService = new ServiceBuilder()
.provider(classOf[RunApi])
RunApi is Java class.
RunApi 是 Java 类。
I'd like to be able pass a variety of classes to provider though. I have a list of them in String format.
不过,我希望能够将各种类传递给提供者。我有一个字符串格式的列表。
Example, if I know the RunApi in String format; e.g. "com.me.RunApi", how can construct the equivalent to above code?
例如,如果我知道 String 格式的 RunApi;例如“com.me.RunApi”,如何构造与上述代码等效的代码?
回答by om-nom-nom
Use forNamemethod:
使用forName方法:
scala> Class.forName("scala.collection.mutable.ArrayBuffer")
res0: java.lang.Class[_] = class scala.collection.mutable.ArrayBuffer

