随笔-生活工作点滴Go基础系列

12. Go 反射

2019-07-06  本文已影响3人  GoFuncChan

Go反射机制

反射具有强大的功能,可在程序运行时检查其所拥有的结构,这是元编程的一种形式,即自己能解析自己。我们可以在运行时通过反射来分析一个结构体,检查其类型和变量(类型和取值)和方法,动态地修改变量和调用方法,这对于没有源代码的包尤其有用,这是一个强大的工具,除非真得有必要,否则应当避免使用或小心使用。

反射的一般使用场景:

反射的两套实现:TypeOf和ValueOf

解析示例:

//使用反射解构一个对象,反射出类的信息,以下为示例结构体
type ObjectA struct {
    Name string
    Age  int
    Desc string
}

func (oa ObjectA) Fa(int) int {
    return 0
}
func (oa ObjectA) Fb(string) bool {
    return true
}
1.ValueOf:访问和修改对象的任意属性的值,访问对象的任意方法

使用示例:

func valueAPI(o ObjectA) {

    oValue := reflect.ValueOf(o)
    fmt.Println("值", oValue) 

    fmt.Println("查看oValue的原始类型:", oValue.Kind()) //struct

    fmt.Println("查看p的所有属性的值")
    for i := 0; i < oValue.NumField(); i++ {
        fValue := oValue.Field(i)
        fmt.Println(fValue.Interface())
    }

    fmt.Println("获得指针value的内容进而获得成员的值:")
    opValue := reflect.ValueOf(&o)
    //opValue是一个People指针的Value,oValue是一个People值的Value
    oValue = opValue.Elem()
    fmt.Println(oValue.Field(1).Interface())

    fmt.Println("修改对象的属性:")
    oValue.FieldByName("Age").SetInt(60)
    fmt.Println(oValue)

    fmt.Println("调用对象的方法:")
    mValue := opValue.MethodByName("Fa")
    mValue.Call([]reflect.Value{reflect.ValueOf(1)})
    fmt.Println(oValue)
}
2.TypeOf:对任意对象的细致入微的类型检测

使用示例:

func typeAPI(obj interface{}) {
    oType := reflect.TypeOf(obj)
    fmt.Println("类型全名:", oType) //main.People

    //原始类型
    oKind := oType.Kind()
    fmt.Println("原始类型:", oKind) //struct

    //类型名称
    fmt.Println("类型名称", oType.Name()) //People

    //属性和方法的个数
    fmt.Println("属性个数:", oType.NumField())  //3
    fmt.Println("方法个数:", oType.NumMethod()) //2

    fmt.Println("全部属性:")
    for i := 0; i < oType.NumField(); i++ {
        structField := oType.Field(i)
        fmt.Println("\t", structField.Name, structField.Type)
    }

    fmt.Println("全部方法:")
    for i := 0; i < oType.NumMethod(); i++ {
        method := oType.Method(i)
        fmt.Println("\t", method.Name, method.Type)
    }

    //fmt.Println("获得父类属性")
    //fmt.Println(oType.FieldByIndex([]int{0, 0}).Name)
}

调用检查执行结果:

func BaseRelect() {
    //valueAPI反射
    fmt.Println("===============reflect.ValueOf检测===============")
    valueAPI(objA)

    //TypeAPI反射
    fmt.Println("===============reflect.TypeOf检测===============")
    typeAPI(objA)


}

//OUTPUT:
===============reflect.TypeOf检测===============
类型全名: base.ObjectA
原始类型: struct
类型名称 ObjectA
属性个数: 3
方法个数: 2
全部属性:
     Name string
     Age int
     Desc string
全部方法:
     Fa func(base.ObjectA, int) int
     Fb func(base.ObjectA, string) bool
===============reflect.ValueOf检测===============
值 {fun 18 gopher}
查看oValue的原始类型: struct
查看p的所有属性的值
fun
18
gopher
获得指针value的内容进而获得成员的值:
18
修改对象的属性:
{fun 60 gopher}
调用对象的方法:
{fun 60 gopher}

应用示例

使用反射获取一个[]interface{}切片里对象的属性值:

示例需求:

所有商品有一些共性:品名、价格
个性无千无万,自行封装出三种商品(以模拟30万种商品)
随意给出一个商品的切片,将每件商品的所有属性信息输出到JSON文件(品名.json)

1.笨办法,使用[]interface{}接收所有元素,并逐一类型断言。

//以下普通为构造结构体:
type Computer1 struct {
    Name   string
    Price  float64
    Cpu    string
    Memory int
    Disk   int
}
type TShirt1 struct {
    Name  string
    Price float64
    Color string
    Size  int
    Sex   bool
}
type Car1 struct {
    Name  string
    Price float64
    Cap   int
    Power string
}

func BaseReflect01() {
 //接收所有struct类型的商品,然后类型断言,一旦类型多则断言断吐血
    products := make([]interface{}, 0)
    computer1 := Computer1{"电脑1", 999.99, "Intel", 1000, 1000}
    shirt1 := TShirt1{"衬衫1", 99, "蓝色", 42, true}
    car1 := Car1{"宝马", 999999.99, 999, "aa"}
    products = append(products, &computer1, &shirt1, &car1)
    
    for _, p := range products {
        name := ""
        switch p.(type) {
        case *Computer1:
            name = p.(*Computer1).Name
        case *TShirt1:
            name = p.(*TShirt1).Name
        case *Car1:
            name = p.(*Car1).Name
        }
        fileName := "/Users/fun/mydemo/text/" + name + ".json"
        is := Struct2JsonFile(fileName, p)
        fmt.Println("输出成功:", is)
    }
}

2.常用办法:使用父struct和接口,调用统一接口方法就可以实现。

//以下为包含商品接口的构造体
type IProduct interface {
    GetName() string
}
type Product struct {
    Name  string
    Price float64
}

func (p *Product) GetName() string {
    return p.Name
}

type Computer2 struct {
    Product
    Cpu    string
    Memory int
    Disk   int
}
type TShirt2 struct {
    Product
    Color string
    Size  int
    Sex   bool
}
type Car2 struct {
    Product
    Cap   int
    Power string
}

func BaseReflect02() {
    iproducts := make([]IProduct, 0)
    computer2 := Computer2{Product{"电脑1", 999.99}, "Intel", 1000, 1000}
    shirt2 := TShirt2{Product{"衬衫1", 99}, "蓝色", 42, true}
    car2 := Car2{Product{"宝马", 999999.99}, 999, "aa"}
    iproducts = append(iproducts, &computer2, &shirt2, &car2)
    
    for _, p := range iproducts {
        name := p.GetName()
        fileName := "/Users/fun/mydemo/text/" + name + ".json"
        is := Struct2JsonFile(fileName, p)
        fmt.Println("输出成功:", is)
    }
}

3.优越的办法,使[]interface{}接收所有struct类型的商品,然后使用反射,简单的获取需要的对象信息。

func BaseReflect03() {  
    products := make([]interface{}, 0)
    computer1 := Computer1{"电脑1", 999.99, "Intel", 1000, 1000}
    shirt1 := TShirt1{"衬衫1", 99, "蓝色", 42, true}
    car1 := Car1{"宝马", 999999.99, 999, "aa"}
    products = append(products, computer1, shirt1, car1)

    for _, p := range products {
        //使用反射方式获取未知类型的对象的值,如果知道属性类型是string则直接用string方法获取
        name := reflect.ValueOf(p).FieldByName("Name").String()
        //如果不确定属性类型,则使用Interface()在类型断言如.(string) / .(int)
        //name := reflect.ValueOf(p).FieldByName("Name").Interface().(string)
        fileName := "/Users/fun/mydemo/text/" + name + ".json"
        is := Struct2JsonFile(fileName, p)
        fmt.Println("输出成功:", is)
    }
}

工具方法:

//将结构体编码到文件的函数
func Struct2JsonFile(fileName string, v interface{}) (is bool) {
    dst, e := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
    if e != nil {
        fmt.Println("打开文件错误:", e)
        return
    }
    defer dst.Close()
    encoder := json.NewEncoder(dst)
    encoder.Encode(v)
    return true
}
上一篇下一篇

猜你喜欢

热点阅读