scala 中的反射。调用方法?

发布于 2024-12-22 20:33:46 字数 454 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入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 as Class<?> in Java.

The Any type is a Scala alternative to Java's Object with extensions: in difference to Java's Object it is a supertype to literally everything in Scala, including primitives.

The Class[_] (short for Class[Any]) is the same type as Java's Class<?>, namely it is the way Java's Class<?> is presented in Scala. Instances of type Class in Scala as much as in Java provide the basic reflection capabilities over the type provided as its generic parameter. I.e. an instance of Class[Something] provides the standard Java's reflection API over class Something. You can use it the same way you do in Java. To get that instance you call the standard method classOf[Something] or instanceOfSomething.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文