PS:我是看视频学习的,然后这是视频地址
http://video.tudou.com/v/XMTc4OTcwMjY4NA==.html
如果大家有需要可以直接去看,感觉讲的满全面的
优点:反射可大大提高程序的灵活性,使得interface有更大的发挥空间
反射使用TypeOf和ValueOf函数从接口中获取目标对象信息
基本应用的一个例子
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)
}