使用反射获取函数名称 [英] Get name of function using reflection

查看:134
本文介绍了使用反射获取函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Go的反射系统来检索函数的名称,但是在调用其类型的Name方法时却得到了一个空字符串.这是预期的行为吗?

I'm trying to use Go's reflection system to retrieve the name of a function but I get an empty string when calling the Name method on its type. Is this the expected behavior?

这是我如何解决问题的简单示例:

This is a simple example of how I approach the problem:

package main

import "fmt"
import "reflect"

func main() {
    typ := reflect.TypeOf(main)
    name := typ.Name()
    fmt.Println("Name of function" + name)
}

推荐答案

解决方案是使用 FuncForPc 会返回*Func.

The solution is to use FuncForPc which returns a *Func.

这将返回"main.main":

package main

import "fmt"
import "reflect"
import "runtime"


func main() {
    name := runtime.FuncForPC(reflect.ValueOf(main).Pointer()).Name()
    fmt.Println("Name of function : " + name)
}

如果要"main",只需将其标记化即可.

If you want "main", just tokenize it.

这篇关于使用反射获取函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆