I have a class such as this:
class NormalClass[T <: NormalClass[T]] {
object One
object Two
}
and I wish to be able to create a new instance of the above class in a typed trait. The following def make in MetaClass creates an instance of T but it lacks the internal objects associated with NormalClass.
trait MetaClass[T <: NormalClass[T]] {
def make:T = this.getClass.getSuperclass.newInstance.asInstanceOf[T]
}
I have two questions, what is the reason for the missing objects and what is the best way, using reflection, to initiate a new class with internal objects from its type
EDIT: More Detail
The problem I am facing is if I then create an instance using make e.g. var f = make and I try to access and object method e.g. f.One.getSomething I get the error value One is not a member of type parameter T.
So I think your problem in particular is the reflection:
Here,
thisis your instance ofMetaClass, and there’s no particular reason to believe that the superclass ofthisis the class you want to instantiate. For example:In this case, the superclass of the object
Foois not aNormalClassat all, it’sjava.lang.Object. As a result, it won’t have members likeOneorTwo, and you’ll get aClassCastExceptionif you try to cast it toT.If you want the
makemethod to instantiate an object of typeT, then you need to get the runtime class ofT, and then use that to create the new instance. You can accomplish this by implicitly acquiring aClassTag: