【Duke】反射编程 036 - PingPongGooo/GoFoundation GitHub Wiki
reflect.TypeOf vs. reflect.ValueOf
reflect.TypeOf返回类型(reflect.Type)
reflect.ValueOf 返回值( reflect.Value)
可以从 reflect.Value 获得类型
通过kind 来判断类型
判断类型 - Kind()
const(
Invalid Kind = iota
Bool
Int
Int8
...
Uint
...
)
利用反射编写灵活的代码
按名字访问结构的成员
reflect.ValueOf(*e).FieldByName("Name")
按名字访问结构的方法
reflect.ValueOf(e).MethodByName(UpdateAge).Call([]reflect.Value{reflect.Valueof(1)})
Struct Tag
type BasicInfo struct{
Name string `json:"name"`
Age int `json:"age"`
}
package reflect
import (
"fmt"
"reflect"
"testing"
)
func TestTypeAndValue(t *testing.T){
var f int64 = 10
t.Log(reflect.TypeOf(f),reflect.ValueOf(f))
t.Log(reflect.ValueOf(f).Type())
}
func CheckType(v interface{}){
t := reflect.TypeOf(v)
switch t.Kind() {
case reflect.Float32, reflect.Float64:
fmt.Println("Float")
case reflect.Int, reflect.Int32, reflect.Int64:
fmt.Println("Interger")
default:
fmt.Println("Unknown",t)
}
}
func TestBasicType(t *testing.T) {
var f float64 = 12
CheckType(f)
}
func TestDeepEqual(t *testing.T) {
a := map[int]string{1:"one",2:"two",3:"three"}
b := map[int]string{1:"one",2:"two",3:"three"}
t.Log("a==b?", reflect.DeepEqual(a,b))
s1 := []int{1,2,3}
s2 := []int{1,2,3}
s3 := []int{2,3,1}
t.Log("s1==s2?", reflect.DeepEqual(s1,s2))
t.Log("s1==s2?", reflect.DeepEqual(s1,s3))
}
type Employee struct {
EmployeeID string
Name string `format:"normal"`
Age int
}
func (e *Employee) UpdateAge(newVal int){
e.Age = newVal
}
type Customer struct {
CookieID string
Name string
Age int
}
func TestInvokeByName(t *testing.T){
e:=&Employee{"1","Mike",30}
t.Logf("Name: value(%[1]v), Type(%[1]T)",reflect.ValueOf(*e).FieldByName("Name"))
if nameField,ok:=reflect.TypeOf(*e).FieldByName("Name");!ok {
t.Error("Failed to get 'Name' filed")
}else {
t.Log("Tag:format",nameField.Tag.Get("format"))
}
reflect.ValueOf(e).MethodByName("UpdateAge").Call([]reflect.Value{reflect.ValueOf(1)})
t.Log("Updated Age:",e)
}