如何在运行时替换Moose对象的方法? [英] How do you replace a method of a Moose object at runtime?

查看:65
本文介绍了如何在运行时替换Moose对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时替换Moose对象的方法? 通过查看 Class::MOP::Method (其中 Moose::Meta::Method 继承自)我得出结论认为,

Is it possible to replace a method of a Moose object at runtime ? By looking at the source code of Class::MOP::Method (which Moose::Meta::Method inherits from) I concluded that by doing

 $method->{body} = sub{ my stuff }

我将能够在运行时替换对象的方法. 我可以使用

I would be able to replace at runtime a method of an object. I can get the method using

 $object->meta->find_method_by_name(<method_name>);

但是,这还没有完全解决.

However, this didn't quite work out.

可以在运行时修改方法吗?而且,用Moose做这件事的方法是什么?

Is it conceivable to modify methods at run time? And, what is the way to do it with Moose?

推荐答案

不管是不是驼鹿,听起来都不是个好主意.

Moose or not, that does not sound like a good idea.

相反,将您的对象设计为具有该方法的访问器.例如,您的类的用户可以使用My::Frobnicator->frobnicator->()来获取并调用frobnicator方法,并使用My::Frobnicator->frobnicator(sub { } )进行设置.

Instead, design your object to have an accessor for the method. For example, users of your class can use My::Frobnicator->frobnicator->() to get and invoke the frobnicator method and use My::Frobnicator->frobnicator(sub { } ) to set it.

这篇关于如何在运行时替换Moose对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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