Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to use a method of an object. Like $myObject->helloWorld().

However there are a couple of methods so I loop through an array of method names and call the method like this:

my $methodName ="helloWorld";
$myObject->$methodNames;

This works quite nice but some objects don't have all methods.

How can I tell whether $myObject has a method called helloWorld or not?

question from:https://stackoverflow.com/questions/2647273/how-can-i-check-if-an-object-has-a-specific-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
248 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the UNIVERSAL::can method of all objects to determine what methods it supports:

if ($myObject->can($methodName)) {
    $myObject->$methodName;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...