dsvjw20866 2017-08-07 10:01
浏览 134

如何在Go中调用未导出的类的方法

I want to invoke http.Server's newConn method in net/http/server.go

func (srv *Server) newConn(rwc net.Conn) *conn {
    c := &conn{
        server: srv,
        rwc:    rwc,
    }
    if debugServerConnections {
        c.rwc = newLoggingConn("server", c.rwc)
    }
    return c
}

Tried to access using reflect but errors occured

conn := ...
server := &http.Server{}

inputs := make([]reflect.Value, 1)
inputs[0] = reflect.ValueOf(conn)
c := reflect.ValueOf(server).MethodByName("newConn").Call(inputs)
panic: reflect: call of reflect.Value.Call on zero Value

goroutine 17 [running, locked to thread]:
reflect.flag.mustBe(0x0, 0x13)
    /usr/local/go/src/reflect/value.go:201 +0xae
reflect.Value.Call(0x0, 0x0, 0x0, 0xc420047d10, 0x1, 0x1, 0x0, 0x0, 0xc4200e82c0)
    /usr/local/go/src/reflect/value.go:300 +0x38

Is there any solution?

  • 写回答

1条回答 默认 最新

  • douchun5976 2017-08-07 10:05
    关注

    TLDR You don't. That's the whole point of not exporting things; to prevent direct access to them.

    Having said that, this question sounds a lot like an XY Problem. Perhaps if you can explain what you're trying to accomplish, we can suggest an alternative approach.

    Longer answer

    This can be possible with reflection (as you're attempting). This should only be done in the absolute rarest of situations, if even then.

    To help with that, please include a complete, reproducible example. The code you've included doesn't compile, so it's impossible to debug.

    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名