使用__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;
然而,正如这个小代码示例所证明的那样,这不能用于访问基类中的属性定义,这对我的特定情况更有用。有没有办法达到我想要的目的?
答案 0 :(得分:9)
请注意,
get_attribute
不会搜索超类,因为您需要使用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;