dongxueji2838 2015-02-18 06:39
浏览 263
已采纳

如何在运行时使用反射更改方法的实现?

I have this type implementation:

type A struct{
  name string
}

func (a A) getName() string {
  return "My name is " + a.name 
}

How I can change implementation of method getName() for this type using reflection? For example, I want use next implementation instead of current:

func newGetName() string {
  return "test reflection"
} 
  • 写回答

2条回答 默认 最新

  • douqing5981 2015-02-18 11:14
    关注

    Go is a compiled language. As such, it's not possible to modify the implementation of things at runtime. What you can do is changing the place function pointers point to:

    var getName func(string) = func(name string) {
        return "my name is " + name
    }
    

    In order to make this work with a structure, you have to resort to a few tricks. First add getName as a member to A:

    type A struct {
        name string
        getName func() string
    }
    

    Then we enclose a pointer to the structure as an implicit (i.e. closed over) parameter:

    foo := &A{name: "Hans"}
    foo.getName = func() string {
        return "my name is " + name
    }
    

    Now you can call A.getName() and the result is "my name is hans". You can use method expressions and many other features just fine, but getName is a structure member and not a method of A, so keep this in mind. When you want to give a new meaning to getName, assign something different to it:

    foo.getName = func() string {
        return "test reflection"
    }
    

    Another idea that is especially applicable if you know in advance what implementations getName could have is to add a new member to A that says what implementation getName currently has and then switch over this variable.

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?