java - Scala 相当于 Java java.lang.Class<T> 对象

标签 java class scala

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

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

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

在 Scala 中,我天真的尝试是:

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

但是当我尝试在 Scala 中使用 Account.class 时,它似乎不喜欢这样。如何在 Scala 中为 Account 类指定 java.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.

但是,classOf[T]getClass 返回的值略有不同,反射(reflect)了 JVM 上类型删除的影响(在 getClass 的情况下)。

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 报告票证“现在”,即两年后的 2011 年 11 月,已修复。
在 2.9.1 中,getClass 现在执行以下操作:

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

)

回到 2009 年:

It would be useful if Scala were to treat the return from getClass() as a java.lang.Class[T] forSome { val T : C } where C is something like the erasure of the static type of the expression on which getClass is called

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 - Scala 相当于 Java java.lang.Class<T> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57191477/

相关文章:

java - 如何在 IntelliJ 中查看未通过参数化测试的完整参数集?

java - 未使用 sj 渲染数据 :select tag in Struts 2

c++ - C++ 中的 class a() 和 class a = class() 有什么区别?

scala - 前置到字符串数组

Scala - 如何创建可用于类型构造函数的单个隐式

java - 添加/删除请求 URL 的参数

java - Package.getImplementationVersion() 返回 NULL

php - CakePHP ServerRequest getQuery() 在 Helper 类中返回空数组

javascript - jQuery - 检查数组中的 2 个元素是否具有相同的类

scala - akka-http。生成文件并发送给客户端