简体   繁体   English

如何从java.lang.Class获取TypeTag

[英]How to get TypeTag from java.lang.Class

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 . 我有一个要求,我需要从java或scala类发送第3方类名到我在scala中编写的API。 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 . 从那个(第三方)类名中,我必须实例化其对象( 也可能具有参数化的构造函数 )并调用其相应的方法。 I made attempts but I am not very well clear with the complete reflection working so it looks like this for now: 我做了一些尝试,但是对于完整的反射工作我还是不太清楚,所以现在看起来像这样:

External (java/scala) class accessing the API : 外部(java / scala)类访问API:

class AnyRandomClass{

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

Here is the attempt to write the scala API : 这是尝试编写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)
}

}

Please help me understand where am I going wrong here , also whats the correct and better way to do it . 请帮助我了解我在哪里出问题了,还有什么正确的更好的方式。

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 . 我有一个要求,我需要从java或scala类发送第3方类名到我在scala中编写的API。 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 从那个(第三方)类名中,我必须实例化其对象(也可能具有参数化的构造函数)并调用其相应的方法

You don't need a TypeTag for this. 您不需要为此的TypeTag Just using Java reflection: 仅使用Java反射:

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

If you do need to use Scala reflection, ClassTag should be enough and trivial to get: 如果确实需要使用Scala反射,则ClassTag应该足够简单,以获得:

ClassTag(clazz)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM