[go学习笔记]三十五、go语言之反射编程

369 阅读1分钟

示例代码请访问:github.com/wenjianzhan…

reflect.TypeOf vs. reflect.ValueOf

  • reflect.TypeOf 返回类型 (reflect.Type)
  • reflect.ValueOf 返回值 (reflect.Value)
  • 可以从 reflect.Value 获取类型
  • 通过 kind 来判断类型

判断类型-Kind()

const (
Invalid Kind =iota
Bool
Int
Int8
Int16
Int32
Int64
Uint
Uint8
Uint16
Uint32
Uint64
...
)

利用反射编写灵活的代码

按名字访问结构的成员

reflect.ValueOf(*e).FieldByName("Name")

按名字访问结构的方法

reflect.ValueOf(e).MethodByName("UpdateAge").Call([]reflect.Value{reflect.ValueOf(1)})

示例代码
```go
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())
}

输出

=== RUN   TestTypeAndValue
--- PASS: TestTypeAndValue (0.00s)
    reflect_test.go:11: int64 10
    reflect_test.go:12: int64
PASS

Process finished with exit code 0

示例代码

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("Int")
	default:
		fmt.Println("Unknow", t)
	}
}

func TestBasicType(t *testing.T) {
	var f float64 = 12
	CheckType(&f)
}

输出

=== RUN   TestBasicType
Unknow *float64
--- PASS: TestBasicType (0.00s)
PASS

Process finished with exit code 0

示例代码

type Employee struct {
	EmployeeID string
	Name       string `format:"normal"`
	Age        int
}

func (e *Employee) UpdateAge(newVal int) {
	e.Age = newVal
}

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' field.")
	} else {
		t.Log("Tag:format", nameField.Tag.Get("format"))
	}
	reflect.ValueOf(e).MethodByName("UpdateAge").Call([]reflect.Value{reflect.ValueOf(1)})
	t.Log("Update Age:", e)
}

输出

=== RUN   TestInvokeByName
--- PASS: TestInvokeByName (0.00s)
    reflect_test.go:55: Name:value(Mike), Type(reflect.Value)
    reflect_test.go:59: Tag:format normal
    reflect_test.go:62: Update Age: &{1 Mike 1}
PASS

Process finished with exit code 0

示例代码请访问:github.com/wenjianzhan…