反射:可以获取信息,可以创建实例,执行函数和方法。

创建实例:
创建实例的前提是具有reflect.Type对象,基于此创建实例。
reflect.TypeOf():TypeOf返回接口中保存的值的类型,TypeOf(nil)会返回nil。
reflect.ValueOf() :这个函数可以返回 reflect.Value类型值
func New(typ Type)Value :返回一个Value类型值,该值持有一个指向类型为typ的新申请的零值的指针,返回值的Type为
PtrTo(typ)

示例:

        
package main

import (
    "fmt"
    "reflect"
)
     
type order struct {
    ordId  int
    customerId int
}
     
func createQuery(q interface{}) {
    t := reflect.TypeOf(q)
    v := reflect.ValueOf(q)
    fmt.Println("Type ", t)
    fmt.Println("Value ", v)     
}
func main() {
    o := order{
    ordId:  456,
    customerId: 56,
}
    createQuery(o)
     
}
     

返回:

  main.order
  Value {456 56}
        

NumField()和Field()方法 一i个返回字段数量,一个返回第几个字段值

示例:

package main
import (
    "fmt"
    "reflect"
)

type order struct {
    ordId      int
    customerId int
}

func CreateQuery(q interface{}) {
    t := reflect.TypeOf(q)
    v := reflect.ValueOf(q)
    fmt.Println("Type ", t)
    fmt.Println("Value ", v)

    c := v.NumField()
    for i := 0; i < c; i++ {
        fmt.Println(v.Field(i))
    }

}
func main() {
    o := order{
        ordId:      456,
        customerId: 56,
    }
    CreateQuery(o)

}

输出:

Type  main.order
Value  {456 56}
456
56



Int()和String()方法
Int和string可以帮我们分别去除reflect.Value作为int64和String

示例:

package main
 
import (
 "fmt"
 "reflect"
)
 
func main() {
 a := 56
 x := reflect.ValueOf(a).Int()
 fmt.Printf("type:%T value:%v\n", x, x)
 b := "Naveen"
 y := reflect.ValueOf(b).String()
 fmt.Printf("type:%T value:%v\n", y, y)
 
}
Last modification:June 6th, 2019 at 04:30 pm
如果觉得我的文章对你有用,请随意赞赏