package main
import (
"fmt"
"reflect"
)
type Company struct {
Title string
Address string
}
type Person struct {
Name string
Age int
Company
}
func (p Person) GetName() string {
return p.Name
}
func (p Person) SetName(s string) {
p.Name = s
}
func main() {
var iii interface{}
a := &Person{Name: "xiao qiang.....", Age: 1, Company: Company{
Title: "AriesDevil",
Address: "ariesdevil@xxoo.com",
}}
iii = a
t := reflect.TypeOf(*a) //必须取值,否则类型为空
fmt.Println(iii,t,t.Name())
v := reflect.ValueOf(iii).Elem() //a需要是引用&
fmt.Println(v, v.Type())
//k := v.Type()
//for i := 0; i < v.NumField(); i++ {
// key := k.Field(i)
// val := v.Field(i)
// fmt.Println(key.Name, val.Type(), val.Interface())
//}
//for i := 0; i < v.NumMethod(); i++ {
// key := k.Method(i)
// val := v.Method(i)
// fmt.Println(key.Name, val.Type(), val.Interface())
//}
//v.FieldByName("Name").Set(reflect.ValueOf("Name"))
//fmt.Println(a.Name)
//方法一:通过反射调用方法
name := v.MethodByName("GetName").Call([]reflect.Value{})
fmt.Println(name,"....")
//方法二:通过反射调用方法,零值
vc := reflect.New(v.Type())
method := vc.MethodByName("GetName")
//in := make([]reflect.Value, 0)
result := method.Call([]reflect.Value{})
fmt.Println(result)
}
参考:
http://studygolang.com/articles/1251
网友评论