Possible duplicate:
How to get Moose to return an instance of a child class instead of its own class for polymorphism
Suppose I have two related classes, MyClass :: A and MyClass :: B, which are subclasses of MyClass. I would like the MyClass constructor to take the file name, read the file and based on the contents of the file, decide if the file is type A or B. Then it must build the object of the corresponding subclass and return it. Edit: Actually, it must call the constructor of the corresponding subclass and return the result.
So, for example, after this code
my $filename = "file_of_type_A.txt"; my $object = MyClass->new($filename);
$object must be an instance of MyClass :: A. This seems to be the correct behavior because $object->isa('MyClass') will always return true. I thought of using introspection to get a list of all the MyClass subclasses, and then try to build them in turn until it works. However, I see no way to modify the Moose constructor to do this. Neither the BUILDARGS hooks nor the BUILD hooks seem suitable.
So, how can I modify the constructor of the Moose class to select the appropriate subclass and delegate the construction to this subclass?
source share