在Moose中,我如何判断一个对象的类是否是另一个对象类的子类?

时间:2010-10-15 00:34:19

标签: perl inheritance introspection moose

假设我有两个对象$obj1$obj2,它们都是Moose类的实例。我想知道以下哪项适用:

  • $obj1的课程与$obj2的相同;
  • $obj1的类是$obj2的子类;
  • $obj1的类是$obj2的超类;
  • 对象的类都不是另一个的子类。

我该怎么做?

2 个答案:

答案 0 :(得分:9)

  1. $obj1的班级与$obj2的班级相同吗?

    ref $obj1 eq ref $obj2;
    
  2. $obj1的类是$obj2的子类吗?

    $obj1->isa(ref $obj2);
    
  3. $obj1的班级是$obj2的超类吗?

    $obj2->isa(ref $obj1);
    
  4. 对象的类都不是另一个的子类。

    见上文。

  5. 更新

    回应有关在运行时应用的角色的评论:

    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 /