如何创建一个新的 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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然,元类就是类。如果您想要该类的实例,只需执行以下操作:
您可能还需要确保 $meta 不会过早被收集。一般来说,您会这样做:
这将保留元类,但如果您不小心,就会泄漏该类。如果你只做一次,那没关系;如果你这样做数千次,你可能会给自己带来麻烦。
最好使用更高级别的东西,例如
Moose::Meta::Class::create_anon_class
或MooseX::Traits
。The metaclass is the class, of course. If you want an instance of that class, just do:
You might also need to make sure that $meta doesn't get collected too soon. Generally, you do this:
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
orMooseX::Traits
.不确定这是否回答了这个问题或您的其他问题
如何在运行时构建 Moose 类,向其添加方法,向其应用角色并实例化一次?您将如何解决这个问题?
位于构建驼鹿在运行时调用类并对其进行调整,但请查看:MooseX: :SingletonMethod
它可能会做你想做的事。或者您可能会发现深入了解我们的工作原理很有用。
该文档确实提供了我在构建此模块时所做的博客文章的链接,因此您可能会发现这些文章也很有帮助。
以下是 MooseX::SingletonMethod 的简短代码示例:
/I3az/
Not sure this answers this or your other SO question
How do I build a Moose class at runtime, add a method to it, apply a role to it and instantiate it once? How would you approach this?
at Building a Moose class at runtime and tuning it but have a look at:MooseX::SingletonMethod
It may do what you want. Or you may find it useful to peer into our it works.
The documentation does provide links to blog posts I made while coming to grips with building this module so you may find those helpful also.
Here is an brief code example of MooseX::SingletonMethod:
/I3az/