Is it possible to create a Class object purely from a generic parameter? For example:
class myclass[T] {
def something(): Class[_ <: T] =
classOf[T] //this doesn't work
}
Since the type will have been erased at runtime, it seems like this a job for manifests, but I haven’t found an example that demonstrates this particular usage. I tried the following, but it doesn’t work either:
class myclass[T] {
def something()(implicit m: Manifest[T]): Class[_ <: T] =
m.erasure //this doesn't work
}
I suspect this failure is due to, as the API points out, there is no subtype relationship between the type of m.erasure‘s result and T.
EDIT: I’m not really interested in what the type T is, I just need an object of type Class[_ <: T] to pass to a method in the hadoop framework.
Any pointers?
You can cast the result of
m.erasureto aClass[T]:This works fine for basic (non-generic) types:
But note what happens if I use an instantiated type constructor like
List[String]forT:Due to erasure, there is only one
Classobject for all the possible instantiations of a given type constructor.Edit
I’m not sure why
Manifest[T].erasurereturnsClass[_]instead ofClass[T], but if I had to speculate, I would say it’s to discourage you from using the methods onClasswhich allow you to compare two classes for equality or a subtype relationship, since those methods will give you wrong answers when theClassis parameterized with an instantiated generic type.For example,
These results might surprise you and/or lead to a bug in your program. Instead of comparing classes this way, you should normally just pass around
Manifests instead and compare them, since they have more information*:As I understand it,
Manifests are meant to supersedeClasses for most use cases… but of course, if you’re using a framework that requires aClass, there’s not much choice. I would suppose that the imposition of casting the result oferasureis just a sort of "acknowledgement of liability" that you’re using an inferior product at your own risk 🙂* Note that, as the documentation for Manifest says, these manifest comparison operators "should be considered approximations only, as there are numerous aspects of type conformance which are not yet adequately represented in manifests."