perl - 驼鹿 (Perl) : access attribute definitions in base classes

标签 perl moose

使用 __PACKAGE__->meta->get_attribute('foo') ,您可以访问 foo给定类中的属性定义,这可能很有用。

#!perl
package Bla;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 1;
no Moose; __PACKAGE__->meta->make_immutable;

package Blub;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 0;
no Moose; __PACKAGE__->meta->make_immutable;

package Blubbel;
use Moose;
extends 'Blub';
no Moose; __PACKAGE__->meta->make_immutable;

package main;
use Test::More;
use Test::Exception;

my $attr = Bla->meta->get_attribute('hui');
is $attr->is_required, 1;

$attr = Blub->meta->get_attribute('hui');
is $attr->is_required, 0;

$attr = Blubbel->meta->get_attribute('hui');
is $attr, undef;
throws_ok { $attr->is_required }
  qr/Can't call method "is_required" on an undefined value/;
diag 'Attribute aus Basisklassen werden hier nicht gefunden.';

done_testing;

然而,正如这个小代码示例所证明的那样,这不能用于访问基类中的属性定义,这对于我的特定情况更有用。有没有办法实现我想要的?

最佳答案

NOTE that get_attribute does not search superclasses, for that you need to use find_attribute_by_name



Class::MOP::Class docs .确实这段代码通过了:
my $attr = Bla->meta->find_attribute_by_name('hui');
is $attr->is_required, 1;

$attr = Blub->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;

$attr = Blubbel->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;

关于perl - 驼鹿 (Perl) : access attribute definitions in base classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6229656/

相关文章:

perl - Pod::Usage 帮助格式化

perl - 如何在 Moose 中创建子类型?

perl - 在 moose 中定义文件句柄属性

perl - Moose 只读属性特征以及如何设置它们?

c - perlbench 在 SPEC 2006 线束之外导致段错误

html - 使用 Perl 解析 html

perl - 为什么 Catalyst 中的这种条件重定向不起作用?

mysql - 创建 Moose 对象以与 Oracle/mysql 数据库交互

perl - 将 Moose 与 Test::Class 一起使用 - 构造函数问题

perl - Perl 中用于单元测试和模拟对象的好的框架是什么?