Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of function using reflection

Tags:

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) } 
like image 615
Laserallan Avatar asked May 24 '12 17:05

Laserallan


People also ask

How to get method name in C#?

Using MethodBase.GetCurrentMethod() method can be used, which returns a MethodBase object representing the currently executing method. That's all about getting the name of the current method in C#.

How to get method using Reflection in C#?

Pass the name of the method as an argument to GetMethod. To invoke GetDetails, use the MethodInfo object to call the Invoke method and pass studentObject as a parameter. And finally, display the details using a String det and also define the class.

What is MethodInfo C#?

The MethodInfo class represents a method of a type. You can use a MethodInfo object to obtain information about the method that the object represents and to invoke the method.


1 Answers

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

This returns "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) } 

If you want "main", just tokenize it.

like image 72
Denys Séguret Avatar answered Sep 30 '22 06:09

Denys Séguret