English 中文(简体)
使用反射查找函数名称
原标题:Get name of function using reflection

我试图使用 Go s 反射系统来检索函数的名称,但在按类型调用名称方法时,我得到了空字符串。这是预期的行为吗?

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

package main

import "fmt"
import "reflect"

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

解决办法是使用"http://golang.org/pkg/runtime/#FuncFORPC" rel=“noreferrer” >FuncForPc ,它返回一个 /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" , 请标记它。

问题回答
package main

import "fmt"
import "runtime"

func main() {
    pc, _, _, _ := runtime.Caller(0)
    fmt.Println("Name of function: " + runtime.FuncForPC(pc).Name())
    fmt.Println()

    // or, define a function for it
    fmt.Println("Name of function: " + funcName())
    x()
}

func funcName() string {
    pc, _, _, _ := runtime.Caller(1)
    return runtime.FuncForPC(pc).Name()
}

func x() {
    fmt.Println("Name of function: " + funcName())
    y()
}

func y() {
    fmt.Println("Name of function: " + funcName())
    z()
}
func z() {
    fmt.Println("Name of function: " + funcName())
}

产出:

函数名称: 主. main

函数名称: 主. main
Name of function: main.x
Name of function: main.y
Name of function: main.z

import runtime

func funcName() string {
    pc, _, _, _ := runtime.Caller(1)
    nameFull := runtime.FuncForPC(pc).Name()    // main.foo
    nameEnd := filepath.Ext(nameFull)           // .foo
    name := strings.TrimPrefix(nameEnd, ".")    // foo
    return name
}

这是用于返回函数名称的测试生产即时实用功能。

注1:我们正在处理从FuncFORPC 调出零指针的可能性。

Note 2: optFuncLevel is just a friendly name for stack frame level. This gives us the flexibility of using this within another layer of utility functions. A direct call from say main would just pass 1 (or nothing since default), but if I am calling FunctionName in a log enriching function, say PrettyLog() that is called from regular code, I would call it as FunctionName(2) in the call from PrettyLog, so the function name returned is the name of the caller of PrettyLog, not PrettyLog itself.

// FunctionName returns the function name of the caller
// optFuncLevel passes the function level to go back up.
// The default is 1, referring to the caller of this function
func FunctionName(optFuncLevel ...int) (funcName string) {
    frameLevel := 1 // default to the caller s frame
    if len(optFuncLevel) > 0 {
        frameLevel = optFuncLevel[0]
    }

    if pc, _, _, ok := runtime.Caller(frameLevel); ok {
        fPtr := runtime.FuncForPC(pc)
        if fPtr == nil {
            return
        }
        // Shorten full function name a bit
        farr := strings.SplitN(fPtr.Name(), "/", 2)
        if len(farr) < 2 {
            return
        }
        return farr[1]
    }

    return
}




相关问题
c# reflection with dynamic class

I need to execute a method "FindAll" in my page. This method returns a list of the object. This is my method that I execute "FindAll". FindAll requires an int and returns an List of these class. ...

Performance overhead of using attributes in .NET

1.. Is there any performance overhead caused by the usage of attributes? Think for a class like: public class MyClass { int Count {get;set;} } where it has 10 attibutes (...

WPF GridView, Display GetType().Name in DisplayMemberBinding

I want include the Type name of each object in my collection from my GridView. I have a collection which has four different types in it that all derive from a base class. Call them, Foo, Bar, Fizz, ...

Testing private method of an abstract class using Reflection

How can I test a private method of an abstract class using reflection (using C#)? I am specifically interested in adapting the code found in this thread. I am aware of the discussion around the ...

Adding Items to ListBox, RadioList, Combobox using reflection

I m trying to add items to a listbox,combobox, radiolist using reflection. The code I have at the moment is as follows: public static Control ConfigureControl(Control control, ControlConfig ctrlconf)...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

热门标签