问题:如何将通用类型从 Scala 传递到 Java,以便JavaContainer中的下一个代码不会像这样失败:
I'm instance of SomeClass
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at main.java.JavaContainer.print(JavaContainer.java:19)
at main.scala.Main$.print(Main.scala:13)
at main.scala.Main$.main(Main.scala:17)
at main.scala.Main.main(Main.scala)
对于这个问题,我有一个给定的(并且不可能从外部 Jar 更改 Java 类),我们称之为:JavaContainer
import java.lang.reflect.ParameterizedType;
public /* You can remove the final marking, the problem is still there */ final class JavaContainer<T> {
private Class<T> clazz;
public JavaContainer(Class<T> clazz) {
this.clazz = clazz;
}
public void print() {
/* This one works */
try {
T unknown = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
/* This one isn't */
Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
System.out.println(persistentClass.getName());
}
}
我也有将用作类型参数的 Java 类:SomeClass
public class SomeClass {
public SomeClass() {
System.out.println("I'm instance of SomeClass");
}
}
现在我想创建一个名为ScalaContainer的Scala类
import main.java.{JavaContainer, SomeClass}
class ScalaContainer[T]()(implicit m:Manifest[T]) {
val clazz = m.runtimeClass.asInstanceOf[Class[T]]
val javaContainer : JavaContainer[T] = new JavaContainer[T](clazz)
}
我们在Main对象中也有我们的 main 方法。
object Main {
def print{
val main = new ScalaContainer[SomeClass]()
main.javaContainer.print()
}
def main(args: Array[String]) {
print
}
}