scala 中的反射。调用方法?
Class<?> clazz = loadClass( "Test" );
Method printSomething = clazz.getDeclaredMethod( "printSomething" );
printSomething.invoke( clazz );
我正在尝试弄清楚如何在 Scala 中做到这一点。我猜我错过了 Scala 处理反射的一些简单的东西。
val clazz = loadClass("Test")
val printSomething = clazz.getDeclaredMethod("printSomething")
printSomething.invoke(clazz)
我的主要问题:Any
对象与 Java 中的 Class
相同吗?
Class<?> clazz = loadClass( "Test" );
Method printSomething = clazz.getDeclaredMethod( "printSomething" );
printSomething.invoke( clazz );
I'm trying to figure out how to do this in Scala. I'm guessing I'm missing something simple with the way Scala handles reflection.
val clazz = loadClass("Test")
val printSomething = clazz.getDeclaredMethod("printSomething")
printSomething.invoke(clazz)
My main question: Is the Any
object the same as Class<?>
in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Any
与 Java 中的Class
不同。Any
类型是 Java 的Object
的 Scala 替代品,并带有扩展:与 Java 的Object
不同,它是 Scala 中几乎所有内容的超类型,包括基元。Class[_]
(Class[Any]
的缩写)与 Java 的Class
类型相同,即它是Java 的Class
在 Scala 中的呈现方式。 Scala 中的Class
类型实例与 Java 中一样,提供了针对作为其泛型参数提供的类型的基本反射功能。即,Class[Something]
的实例通过类Something
提供标准 Java 反射 API。您可以像在 Java 中一样使用它。要获取该实例,您可以调用标准方法classOf[Something]
或instanceOfSomething.getClass
。Scala 2.10 提供了主要针对类型擦除问题解决方案的扩展反射功能,这是非常稳定的快照版本,您可以随时下载。此扩展 API 通过对象 scala.reflect.runtime.Mirror 提供。互联网上还没有太多关于它的文档,但您可以在 StackOverflow 上找到一些不错的信息。
Any
is not the same asClass<?>
in Java.The
Any
type is a Scala alternative to Java'sObject
with extensions: in difference to Java'sObject
it is a supertype to literally everything in Scala, including primitives.The
Class[_]
(short forClass[Any]
) is the same type as Java'sClass<?>
, namely it is the way Java'sClass<?>
is presented in Scala. Instances of typeClass
in Scala as much as in Java provide the basic reflection capabilities over the type provided as its generic parameter. I.e. an instance ofClass[Something]
provides the standard Java's reflection API over classSomething
. You can use it the same way you do in Java. To get that instance you call the standard methodclassOf[Something]
orinstanceOfSomething.getClass
.Extended reflection capabilities primarily targeted at the solution of the type erasure issue are coming with Scala 2.10, pretty stable snapshot versions of which you can always download. This extended API is provided thru the object
scala.reflect.runtime.Mirror
. There's not much documentation on it in the internet yet, but you can find some decent information here on StackOverflow.