scala> import java.util.Properties
import java.util.Properties
scala> trait Foo extends Properties
defined trait Foo
scala> classOf[Foo]
res0: java.lang.Class[Foo] = interface Foo
scala> class FooP extends Foo
defined class FooP
scala> classOf[FooP]
res1: java.lang.Class[FooP] = class FooP
scala> classOf[Properties with Foo]
<console>:7: error: class type required but java.util.Properties with Foo found
classOf[Properties with Foo]
^
scala> new Properties with Foo
res2: java.util.Properties with Foo = {}
scala> res2.getClass
res3: java.lang.Class[_] = class $anon$1
Is there a way of getting class of 'Properties with Foo' without creating an instance or new class?
classOf[X]
only works if X
corresponds to a physical class. T with U
is a compound type, and doesn't correspond to a class.
You can use Manifests to determine the erasure of a type. The type erasure of T with U
is T
.
scala> trait T
defined trait T
scala> trait U
defined trait U
scala> manifest[T with U]
res10: Manifest[T with U] = T with U
scala> manifest[T with U].erasure
res11: java.lang.Class[_] = interface T
Here you can see that List[Int]
and List[_]
have the same erasure:
scala> classOf[List[_]]
res13: java.lang.Class[List[_]] = class scala.collection.immutable.List
scala> classOf[List[Int]]
res14: java.lang.Class[List[Int]] = class scala.collection.immutable.List
scala> classOf[List[Int]] == classOf[List[_]]
res15: Boolean = true
No it is not possible because "X with Y" is an anonymous definition in your example. This is not the case for "class X extends Z with Y" of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With