dounai9592 2014-03-13 09:17 采纳率: 100%
浏览 43
已采纳

通过反射获取阴影方法

How can I get the shadowed methods via reflection?

In the code below I'm using MethodByName to get method Test() on type B, but I would like to get the shadowed method Test() from b.A as well, so I can call both of them.

package main

import (
    "fmt"
    "reflect"
)

type A struct {}
type B struct {
    A
}

func (self *A) Test() {
    fmt.Println("I'm A")
}
func (self *B) Test() {
    fmt.Println("I'm B")
}

func main() {
    b := &B{}
    b.Test()   // This one shadows b.A.Test()
    b.A.Test() // but its ok to call like this

    // via reflection
    val := reflect.ValueOf(b)
    val.MethodByName("Test").Call([]reflect.Value{})
}

Code available here: http://play.golang.org/p/6YPLy2dmMb

  • 写回答

2条回答 默认 最新

  • dongyunshan4066 2014-03-13 09:46
    关注

    If you have an embedded struct and shadowing, you can always get the field as if it were a member variable with the same name as the type of the embedded struct, this is shown by your line b.A.Test().

    So what do we do? Use reflect.Value.FieldByName to get the field. With your exact setup it's a bit janky. You can't use FieldByName on a pointer to a struct.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type A struct{}
    type B struct {
        A
    }
    
    func (self *A) Test() {
        fmt.Println("I'm A")
    }
    func (self *B) Test() {
        fmt.Println("I'm B")
    }
    
    func main() {
        b := &B{}
        b.Test()
        b.A.Test()
    
        val := reflect.ValueOf(b)
        subVal := val.Elem().FieldByName("A").Addr()
        subVal.MethodByName("Test").Call([]reflect.Value{})
        val.MethodByName("Test").Call([]reflect.Value{})
    }
    

    As seen, it's a bit ugly. You first need to call Elem to get the value val points to, then get the field, then get the pointer to the field because A.Test is actually on (*A), and not A. While Go pointers are normally transparent, it doesn't apply to reflection, unfortunately, so you have to do all explicit addressing/dereferencing yourself, but if you understand pointers it's pretty straightforward.

    Edit: Playground link to the code above

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值