GO语言的reflection

PS:我是看视频学习的,然后这是视频地址
http://video.tudou.com/v/XMTc4OTcwMjY4NA==.html
如果大家有需要可以直接去看,感觉讲的满全面的

优点:反射可大大提高程序的灵活性,使得interface有更大的发挥空间
反射使用TypeOfValueOf函数从接口中获取目标对象信息
基本应用的一个例子

package main

import "fmt"
import "reflect"

type User struct{
  Id int
  Name string
  Age int
}

func (u User) Hello(){
   fmt.Println("Hellow World!")
}

//translate by value
func Info(o interface{}){
   t:=reflect.TypeOf(o)
   fmt.Println("Type:",t.Name)


  //check up if the type is right
   if k:=t.Kind();k!=reflect.Struct{
         fmt.Println("LL")
         return 
   }

   v:=reflect.ValueOf(o)
   fmt.Println("Fields:")

   for i:=0;i<t.NumField();i++{
    f:=t.Field(i)
    val:=v.Field(i).Interface()
    fmt.Println(f.Name,f.Type,val)
   }//get the num of field

    for i:=0;i<t.NumMethod();i++{
    m:=t.Method(i)
    fmt.Println(m.Name,m.Type)
   }//get the num of method
}

func main(){
  u:=User{1,"OK",12}
  Info(u)
}

针对匿名
反射包通过序号的形式取出匿名

package main

import "fmt"
import "reflect"

type User struct{
  Id int
  Name string
  Age int
}

type Manager struct{
  User
  title string
}

func main(){
  m:=Manager{User:User{1,"OK",12},title:"123"}
  t:=reflect.TypeOf(m)

  fmt.Println(t.Field(0))
  fmt.Println(t.Field(1))//the last can tell us if is anonymous

  fmt.Println(t.FieldByIndex([]int{0,1}))//change the second one can choose the 

information that you want
}

通过反射改变数据
简单例子1:修改自定义类型

package main

import "fmt"
import "reflect"


func main(){
  x:=123
  v:=reflect.ValueOf(&x)//get the address 
  v.Elem().SetInt(999)
  fmt.Println(x)
}

简单例子2:修改struct类型

package main

import "fmt"
import "reflect"

type User struct{
  Id int
  Name string
  Age int
}

func Set(o interface{}){
   v:=reflect.ValueOf(o)

   if v.Kind()==reflect.Ptr&&!v.Elem().CanSet(){
    fmt.Println("XX")
    return
   }else{
    v=v.Elem()
   }

   if f:=v.FieldByName("Name");f.Kind()==reflect.String{
     f.SetString("BYEBYE")
   }    
}


func main(){
  u:=User{1,"OK",12}
  Set(&u)
  fmt.Println(u)
}

反射进行方法的调用

package main

import "fmt"
import "reflect"

type User struct{
  Id int
  Name string
  Age int
}

func (u User) Hello(name string){
   fmt.Println("Hello",name," my name is ",u.Name)
}

func main(){
  u:=User{1,"OK",12}
  v:=reflect.ValueOf(u)
  mv:=v.MethodByName("Hello")

  args:=[]reflect.Value{reflect.ValueOf("joe")}
  mv.Call(args)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值