这个问题最好通过一个例子来解释:
在 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 对象?
最佳答案
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 expressionT.class
.
UsingclassOf[T]
is convenient when you have a type that you want information about, whilegetClass
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/