如何通过scala反射创建带有类型参数的实例?

How to create instance with type parameter through scala reflection?

这是我的代码

package a1

trait Algorithm[T] {
  def someMethod(a: Int): T
}
package b2

import a1.Algorithm

class Word2Vec[T] extends Algorithm[T] {
  def someMethod(a: Int): T = a.asInstanceOf[T]
}
package c3

import a1.Algorithm

object Main {
  def main(args:Array[String]) = {
    val word2vec:Algorithm[Float] = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[Float]]
    val a = word2vec.someMethod(123)
    println(a)
  }
}

我得到了这个:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
    at scala.runtime.BoxesRunTime.unboxToFloat(BoxesRunTime.java:107)
    at c3.Main$.main(Main.scala:8)
    at c3.Main.main(Main.scala)

顺便说一句,我得到一个字符串名称时如何得到一个类型。我有一个 "int" 并且我想传递类型 Int 作为泛型

的类型参数

以下带有 Int 的代码不会抛出异常

val word2vec = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[Int]]
val a = word2vec.someMethod(123)
println(a) // 123

_

val word2vec = Class.forName("b2.Word2Vec").newInstance().asInstanceOf[Algorithm[_]]
val a = word2vec.someMethod(123)
println(a) // 123

其实Class.forName + newInstance不是Scala反射,而是Scala中使用的Java反射。 Scala 反射是不同的。

by the way,How could I get a type when I get a string name. I have an "int" and I want to pass type Int as the type parameter for generic

我不确定这可以通过 Java 反射来完成。使用 Scala 反射

import scala.reflect.runtime.universe._
val mirror = runtimeMirror(this.getClass.getClassLoader)
val classSymbol = mirror.staticClass("b2.Word2Vec") // class Word2Vec
// if string is "int"
internal.typeRef(NoPrefix, classSymbol, List(typeOf[Int])) // Word2Vec[Int]
// if string is "float"
internal.typeRef(NoPrefix, classSymbol, List(typeOf[Float])) // Word2Vec[Float]