假设我有两个对象$obj1
和$obj2
,它们都是Moose类的实例。我想知道以下哪项适用:
$obj1
的课程与$obj2
的相同; $obj1
的类是$obj2
的子类; $obj1
的类是$obj2
的超类; 我该怎么做?
答案 0 :(得分:9)
$obj1
的班级与$obj2
的班级相同吗?
ref $obj1 eq ref $obj2;
$obj1
的类是$obj2
的子类吗?
$obj1->isa(ref $obj2);
$obj1
的班级是$obj2
的超类吗?
$obj2->isa(ref $obj1);
对象的类都不是另一个的子类。
见上文。
回应有关在运行时应用的角色的评论:
package My::X;
use Moose; use namespace::autoclean;
sub boo { }
__PACKAGE__->meta->make_immutable;
package My::Y;
use Moose; use namespace::autoclean;
extends 'My::X';
__PACKAGE__->meta->make_immutable;
package My::Z;
use Moose::Role; use namespace::autoclean;
requires 'boo';
package main;
use Test::More tests => 2;
use Moose::Util qw( apply_all_roles );
my $x = My::X->new;
my $y = My::Y->new;
ok($y->isa(ref $x), 'Before role was applied at runtime');
apply_all_roles($x, 'My::Z');
ok($y->isa(ref $x), 'After role was applied at runtime');
输出:
1..2 ok 1 - Before role was applied at runtime not ok 2 - After role was applied at runtime # Failed test 'After role was applied at runtime' at C:\Temp\t.pl line 36. # Looks like you failed 1 test of 2.
答案 1 :(得分:5)
使用Class::MOP
中的Moose
基础,您可以反省所有这些信息。
例如:
{
package Daddy;
use Moose;
}
{
package Kid;
use Moose;
extends 'Daddy';
}
my $son = Kid->new;
my $daughter = Kid->new;
my $sons_class = ($son->meta->class_precedence_list)[0];
my $daughters_class = ($daughter->meta->class_precedence_list)[0];
my @sons_subclasses = $son->meta->subclasses; # or better...
my @daughters_subclasses = $daughter->meta->direct_subclasses;
my @sons_superclasses = $son->meta->superclasses;
my @Daddies_children = Daddy->meta->direct_subclasses;
另请参阅此SO问题/答案How can I find all the packages that inherit from a package in Perl?
/ I3az /