Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object has a particular method?

Tags:

go

go-reflect

In Go, how do you check if an object responds to a method?

For example, in Objective-C this can be achieved by doing:

if ([obj respondsToSelector:@selector(methodName:)]) { // if method exists   [obj methodName:42]; // call the method } 
like image 955
nishanthshanmugham Avatar asked Apr 16 '15 19:04

nishanthshanmugham


People also ask

How can you tell if an object has a specific property?

The first way is to invoke object. hasOwnProperty(propName) . The method returns true if the propName exists inside object , and false otherwise. hasOwnProperty() searches only within the own properties of the object.

How do you check if an object contains a value?

You can use Object. values(): The Object. values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

How do you check if an object contains a key?

How to Check if an Object Has a key in JavaScript with the in Operator. You can use the JavaScript in operator to check if a specified property/key exists in an object. It has a straightforward syntax and returns true if the specified property/key exists in the specified object or its prototype chain.


1 Answers

A simple option is to declare an interface with just the method you want to check for and then do a type assert against your type like;

 i, ok := myInstance.(InterfaceImplementingThatOneMethodIcareAbout)  // inline iface declaration example  i, ok = myInstance.(interface{F()}) 

You likely want to use the reflect package if you plan to do anything too crazy with your type; http://golang.org/pkg/reflect

st := reflect.TypeOf(myInstance) m, ok := st.MethodByName("F") if !ok {     // method doesn't exist } else {     // do something like invoke m.F }    
like image 64
evanmcdonnal Avatar answered Oct 13 '22 06:10

evanmcdonnal