java - 如何从 java.lang.Class 获取 TypeTag

标签 java scala reflection

我有一个要求,我需要从 java 或 scala 类发送第 3 方类名到我在 scala 中编写的 API。从那个(第 3 方)类名我必须实例化它的对象(也可能有一个参数化的构造函数)并调用它相应的方法。我做了一些尝试,但我不太清楚完整的反射是如何工作的,所以现在看起来像这样:

访问 API 的外部 (java/scala) 类:

class AnyRandomClass{

MyAPI api = new API();
api.getThirPartyObject(ThirdPartyClassName);
}

这是编写 scala API 的尝试:

package mypckg

import scala.reflect.runtime._
import scala.reflect.runtime.universe._

class MyAPI{
def getThirdPartyObject ={
   val u = universe
   val m = u.runtimeMirror(getClass.getClassLoader)
   //throws error : type staticClass is not a member of mypckg.MyAPI.u.Mirror
   m.runtimeClass(typeOf[m.staticClass(clazz.getName).selfType].typeSymbol.asClass)
}

}

请帮助我了解我哪里出错了,还有什么是正确和更好的方法。

最佳答案

I have a requirement where I need to send from java or scala class a 3rd party class name to an API which I am writing in scala . From that (3rd party) class name I have to instantiate its object (which might have a parameterized constructor as well) and call its corresponding methods

为此您不需要 TypeTag。仅使用 Java 反射:

val constructors = clazz.getConstructors 
// see also getConstructor, getDeclaredConstructors, and getDeclaredConstructor
val constructor = // select the constructor you need
constructor.newInstance(parameters)
// etc

如果您确实需要使用 Scala 反射,ClassTag 应该足够简单了:

ClassTag(clazz)

关于java - 如何从 java.lang.Class 获取 TypeTag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891410/

相关文章:

c# - 如何使用 Reflection.Emit 添加引用

java - 在将消息发送到 ActiveMQ 之前对消息进行池化

java - 如何找到第一个 JsonArray DTD

java - Akka 是否支持没有对象序列化的进程内消息传递?

scala - 如何使用 akka-http 将 html 文件作为正确的内容正确地提供给浏览器?

scala - 覆盖继承的构造函数字段时的差异?

java - 智能标注

c# - 如何为运行时类型创建 List<type>?

java - 运行后如何使用用户名、密码和 url 连接到 postgres docker 镜像?

scala - 在 Scala 中,如何编写一个带有构造函数的类,而不是所有参数都是类成员?