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 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)