如何创建一个新的Moose类并在运行时实例化该类的对象? [英] How do I make a new Moose class and instantiate an object of that class at runtime?

查看:226
本文介绍了如何创建一个新的Moose类并在运行时实例化该类的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Moose :: Meta :: Class-> create 创建元类后,如何实例化一个真正的Moose类作为元类?
(我需要创建元类,因为我也想应用一些角色。)

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 metaclass also because I also want to apply some roles to it.)

推荐答案

元类是类,当然。如果你想要该类的实例,只需:

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

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

您可能还需要确保$ meta不会太快收集。一般来说,您可以这样做:

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.

更好地使用像 Moose :: Meta这样的更高层次的东西: :Class :: create_anon_class MooseX :: Traits

这篇关于如何创建一个新的Moose类并在运行时实例化该类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆