英文:
How do i get the method argument names
问题
我有一个很好的函数,可以打印给定类型中给定方法的一些信息,这是一个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 //无法找到一种方法来获取函数接受的每个参数的有序名称切片
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?")
}
}
英文:
I have this nice function that prints some info about a given method in a given type, here is a goplay
it does all i need except i can't find a way to get the method argument names,any idea to achieve that?
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?")
}
}
答案1
得分: 3
局部变量的名称(包括函数参数)只是为了程序员方便使用,编译器在生成代码时会丢弃它们。无法检索参数名称,因为它们在编译后的代码中不可用。
英文:
The names of local variables (including function arguments) are just for the programmer; the compiler discards them when it generates code. There is no way to retrieve argument names as they are not available in the compiled code.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论