我有这个很好的函数,可以打印给定类型中给定方法的一些信息,这里是goplay
它完成了我所需要的一切,除了我找不到方法来获取方法参数名称,任何想法实现它?
func AnalyzeMethod(instance interface {},methodName string){
m,ok := reflect.ValueOf(instance).Type().MethodByName(methodName)
if ok{
isVariadic := m.Type.IsVariadic()
var VariadicIndex int
var VariadicType reflect.Type
var FirstPositionalIndex int
var LastPositionalIndex int
var ArgsLength int = m.Type.NumIn()-1
//var []string ArgumentNames //can't find a way to get an ordered slice of names of every argument that the function takes
if ArgsLength>0{
FirstPositionalIndex = 1
}
if isVariadic{
VariadicIndex = ArgsLength
VariadicType = m.Type.In(VariadicIndex)
LastPositionalIndex = ArgsLength-1
} else {
VariadicIndex = -1
LastPositionalIndex = ArgsLength
}
fmt.Println("ArgsLength:",ArgsLength)
fmt.Println("FirstPositionalIndex:",FirstPositionalIndex)
fmt.Println("LastPositionalIndex:",LastPositionalIndex)
fmt.Println("Variadic:",isVariadic)
fmt.Println("VariadicIndex:",VariadicIndex)
fmt.Println("VariadicType:",VariadicType)
fmt.Println("ArgumentNames","How?")
}
}
答案 0 :(得分:3)
局部变量(包括函数参数)的名称仅供程序员使用;编译器在生成代码时会丢弃它们。无法检索参数名称,因为它们在编译的代码中不可用。