这个问题最好用一个例子来解释:

在JPA EntityManager的Java中,我可以执行以下操作(Account是我的实体类):

Account result = manager.find(Account.class, primaryKey);

在Scala中,我天真的try 是:

val result = manager.find(Account.class, primaryKey)

但当我try 在Scala中使用Account.class时,它似乎不是这样的.如何指定java.Scala中Account类的lang.Class对象?

推荐答案

根据"The Scala Type System",

val c = new C
val clazz = c.getClass              // method from java.lang.Object
val clazz2 = classOf[C]             // Scala method: classOf[C] ~ C.class
val methods = clazz.getMethods      // method from java.lang.Class<T>

The classOf[T] method returns the runtime representation for a Scala type. It is analogous to the Java expression T.class.
Using classOf[T] is convenient when you have a type that you want information about, while getClass is convenient for retrieving the same information from an instance of the type.

然而,在getClass中,classOf[T]getClass返回的值略有不同,这反映了类型擦除对JVM的影响.

scala> classOf[C]
res0: java.lang.Class[C] = class C

scala> c.getClass
res1: java.lang.Class[_] = class C

这就是为什么following will not work:

val xClass: Class[X] = new X().getClass //it returns Class[_], nor Class[X]

val integerClass: Class[Integer] = new Integer(5).getClass //similar error

有一个ticket regarding the return type of getClass.

(James Moore reports that the ticket is "now", ie Nov. 2011, two years later, fixed.
In 2.9.1, getClass now does:

scala> "foo".getClass 
       res0: java.lang.Class[_ <: java.lang.String] = class java.lang.String

)

回到2009年:

如果Scala将getClass()的返回视为java,这将非常有用.lang.Class[T]对于某些{val T:C},其中C类似于对调用getClass的表达式的静态类型的擦除

It would let me do something like the following where I want to introspect on a class but shouldn't need a class instance.
I also want to limit the types of classes I want to introspect on, so I use Class[_ <: Foo]. But this prevents me from passing in a Foo class by using Foo.getClass() without a cast.

注:关于getClass,一个可能的解决办法是:

class NiceObject[T <: AnyRef](x : T) {
  def niceClass : Class[_ <: T] = x.getClass.asInstanceOf[Class[T]]
}

implicit def toNiceObject[T <: AnyRef](x : T) = new NiceObject(x)

scala> "Hello world".niceClass                                       
res11: java.lang.Class[_ <: java.lang.String] = class java.lang.String

Java相关问答推荐

表格栏上的事件过滤器在PFA中不起作用

Android -如何修复Java.time.zone. ZoneRulesExcept:未知时区ID:Europe/Kyiv

使用Apache Poi MQLSlideShow,在XSLFTable表中,我们可以在文本段落后面的每个单元格中包含圆角矩形吗?

查找最大子数组的和

JPackaged应用程序启动MSI调试,然后启动System. exit()

了解Android Studio中的调试器输出

屏蔽字母数字代码的Java正则表达式

在JavaFX项目中注册组合框的控件FX验证器时,模块系统出错

Java中的死锁及其重入锁和锁

Helidon 4和Http API

如何使用Jackson将XML元素与值和属性一起封装

使用Room Database删除Jetpack合成中的所有项目后,UI未重新合成

对字符串长度进行排序,但颠倒了顺序(最长字符串在前)

在Eclipse中调试未导出的JDK模块的Java包

如何在构建Gradle项目时排除com.google.guava依赖项的一个变体

如何将Pane的图像快照保存为BMP?

如何在我的世界中为互动增加冷却时间?

如何在@CsvSource中传递空格作为值

FETCH类型设置为LAZY,但它仍会发送第二个请求

带有可选部分的Java DateTimeForMatter