如何确定对象是否在Perl中实现方法?

时间:2021-01-04 07:30:12

I've got a polymorphic array of objects which implement two (informal) interfaces. I want to be able to differentiate them with reflection along the lines of:

我有一个实现两个(非正式)接口的多态对象数组。我希望能够通过以下方式区分它们:

if (hasattr(obj, 'some_method')) {
    # `some_method` is only implemented by one interface.
    # Now I can use the appropriate dispatch semantics.
} else {
    # This must be the other interface.
    # Use the alternative dispatch semantics.
}

Maybe something like this works?:

也许这样的东西有效吗?:

if (*ref(obj)::'some_method') {
    # ...

I have difficulty telling when the syntax will try to invoke a subroutine and when it will return a subroutine reference. I'm not too familiar with package symbol tables ATM and I'm just trying to hack something out. :-)

我很难说出语法何时会尝试调用子例程以及何时返回子例程引用。我不太熟悉包装符号表ATM,我只是试图破解一些东西。 :-)

Thanks in advance!

提前致谢!

1 个解决方案

#1


use Scalar::Util qw(blessed);
if( blessed($obj) and $obj->can('some_method') ){ 

}

"can" here is a method inherited by all classes from UNIVERSAL . Classes can override this method, but its not a good idea to.

“can”这里是UNIVERSAL所有类继承的方法。类可以覆盖此方法,但它不是一个好主意。

Also, "can" returns a reference to the function, so you can do:

此外,“can”返回对函数的引用,因此您可以执行以下操作:

$foo->can('some_method')->( $foo , @args );

or

my $sub = $foo->can('some_method'); 
$foo->$sub( @args ); 

Edit Updated Chain Syntax, thanks to Brian Phillips

编辑更新的链语法,感谢Brian Phillips

#1


use Scalar::Util qw(blessed);
if( blessed($obj) and $obj->can('some_method') ){ 

}

"can" here is a method inherited by all classes from UNIVERSAL . Classes can override this method, but its not a good idea to.

“can”这里是UNIVERSAL所有类继承的方法。类可以覆盖此方法,但它不是一个好主意。

Also, "can" returns a reference to the function, so you can do:

此外,“can”返回对函数的引用,因此您可以执行以下操作:

$foo->can('some_method')->( $foo , @args );

or

my $sub = $foo->can('some_method'); 
$foo->$sub( @args ); 

Edit Updated Chain Syntax, thanks to Brian Phillips

编辑更新的链语法,感谢Brian Phillips