如何检查一个对象是否有特定的方法? [英] How to check if an object has a particular method?

查看:90
本文介绍了如何检查一个对象是否有特定的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go中,如何检查对象是否响应方法?例如,在Objective-C中,可以通过执行以下操作来实现:

  if([obj respondsToSelector:@selector(methodName :)]){// if method exists 
[obj methodName:42 ]。 //调用方法
}


解决方案

A简单的选择是用你想检查的方法声明一个接口,然后对你的类型进行类型断言,比如;

pre $ code > i,ok:= myInstance。(InterfaceImplementingThatOneMethodIcareAbout)
// inline iface delcataration example
i,ok = myInstance。(interface {F()})

如果您打算对您的类型执行任何过于疯狂的操作,您可能希望使用 reflect 包; http://golang.org/pkg/reflect

  st:= reflect.TypeOf(myInstance)
m,ok:= st.MethodByName(F)
if!ok {
//方法不存在
}
//做类似invoke m


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
}

解决方案

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 delcataration 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
}
// do something like invoke m

这篇关于如何检查一个对象是否有特定的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆