vendredi 3 novembre 2017

golang How to call an unexported package function

How to call an unexported package function, for example package function hello() is defined as:

package testlib

import "fmt"

func hello() {
    fmt.Println("Hello testlib")
}

And there is calling from main package:

package main

import (
  _ "reflect"

    "testlib"
)

func main() {
    testlib.hello()
}

And of course, this program is incorrect. I have googled much, many people mentioned that reflect package could be used to invoke an unexported function, like:

obj := ... (some object)
val := reflect.ValueOf(obj);
fun := val.MethodByName("hello")
fun.Call([]reflect.Value{})

But all examples are based on an object (i.e,. a struct), not a package. My problem is that I am going to call a package function, not an object function. thanks.





Aucun commentaire:

Enregistrer un commentaire