问题:我如何将泛型类型从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类,将被用作类型参数: someeclass
public class SomeClass {
public SomeClass() {
System.out.println("I'm instance of SomeClass");
}
}
现在我要创建一个Scala类,名为ScalaContainer
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 object中也有main方法
object Main {
def print{
val main = new ScalaContainer[SomeClass]()
main.javaContainer.print()
}
def main(args: Array[String]) {
print
}
}
…我试着想象你的代码和它在做什么。它让我想起使用Hibernate和泛型dao,我已经做了很多,所以我想说你应该看看http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/reflect/TypeToken.html,它会按照你设置的方式打印SomeClass。这里还有TypeTools https://github.com/jhalterman/typetools
我认为如果我正确理解你的问题,这应该会让你走上正确的道路。