gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:18:18 25 4
gpt4 key购买 nike

我有一个要求,我需要从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com