使用 __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 usefind_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/