dongzexi5125 2014-08-29 08:24
浏览 19
已采纳

反思问题

I'm trying to use reflection in go. Why doesn't this code list the methods? It lists the fields.

is this the problem? "value interface{}" I'm not sure how to pass a generic struct/class/type to a function. Normally I would just pass an Object.

(I'm totally new at this. I'm a C# programmer)

package main

import (
"fmt"
"reflect"
)

func main() {
    var B TestType = TestType{TestString: "Hello", TestNumber: 3}
    ListMethods(B)
}

func ListMethods(value interface{}) {

    fooType := reflect.TypeOf(value)

    for i := 0; i < fooType.NumMethod(); i++ {
        method := fooType.Method(i)
        fmt.Println("Method = " + method.Name)
    }

    for i := 0; i < fooType.NumField(); i++ {
        field := fooType.Field(i)
        fmt.Println("Field = " + field.Name)
        fmt.Println(reflect.ValueOf(value).Field(i))
    }
}

type TestType struct {
    TestString string
    TestNumber int
}

func (this *TestType) TestFunction() {
    fmt.Println("Test")
}
  • 写回答

1条回答 默认 最新

  • doujiyun0041 2014-08-29 08:39
    关注

    Because you are passing a type and you declared a method to the pointer of the type.

    https://play.golang.org/p/B0NdVyxGxt

    Look at this example extended from yours:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        var B TestType = TestType{TestString: "Hello", TestNumber: 3}
        ListMethods(B)
    }
    
    func ListMethods(value interface{}) {
    
        fooType := reflect.TypeOf(value)
        ptrFooType := reflect.PtrTo(fooType)
    
        for i := 0; i < fooType.NumMethod(); i++ {
            method := fooType.Method(i)
            fmt.Println("Method = " + method.Name)
        }
    
        for i := 0; i < ptrFooType.NumMethod(); i++ {
            method := ptrFooType.Method(i)
            fmt.Println("* Method = " + method.Name)
        }
    
        for i := 0; i < fooType.NumField(); i++ {
            field := fooType.Field(i)
            fmt.Println("Field = " + field.Name)
            fmt.Println(reflect.ValueOf(value).Field(i))
        }
    }
    
    type TestType struct {
        TestString string
        TestNumber int
    }
    
    func (this *TestType) TestFunctionPtr() {
        fmt.Println("Test")
    }
    
    func (this TestType) TestFunction() {
        fmt.Println("Test Non Ptr")
    }
    

    Notice how the *Type can access also the Type Methods. But Type cannot access to *Type Methods.

    To convert from Type to *Type I have used the reflect.PtrTo(Type).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条