How do I make a new Moose class and instantiate an object of that class at runtime?

前端 未结 2 1337
迷失自我
迷失自我 2021-01-24 10:15

After creating a metaclass using Moose::Meta::Class->create, how do I instantiate a real Moose class with that class as a metaclass? (I need to create the metacl

2条回答
  •  一整个雨季
    2021-01-24 11:00

    The metaclass is the class, of course. If you want an instance of that class, just do:

    my $instance = $meta->name->new
    

    You might also need to make sure that $meta doesn't get collected too soon. Generally, you do this:

    $meta->add_method( meta => sub { $meta } );
    

    That will keep the metaclass around, but you're going to leak the class if you aren't careful. If you only do this once, it won't matter; if you do it thousands of times, you could get yourself into trouble.

    Much better to use something higher-level like Moose::Meta::Class::create_anon_class or MooseX::Traits.

提交回复
热议问题