我們先看看什么是反射,它有什么用。
我們先看卡wiki上關(guān)于反射的介紹缺谴。 鏈接為https://en.wikipedia.org/wiki/Reflection_(computer_programming)
In computer science, reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.[1]
反射的主要作用:Reflection helps programmers make generic software libraries to display data, process different formats of data, perform serialization or deserialization of data for communication, or do bundling and unbundling of data for containers or bursts of communication.
通俗的講, 反射是指在程序運行期對程序數(shù)據(jù)結(jié)構(gòu)和行為本身進(jìn)行訪問和修改的能力但惶。
支持反射的語言可以在程序編譯期將變量的反射信息耳鸯,如字段名稱、類型信息膀曾、結(jié)構(gòu)體信息等整合到可執(zhí)行文件中县爬,并給程序提供接口訪問反射信息,這樣就可以在程序運行期獲取類型的反射信息添谊,并且有能力修改它們财喳。
Go語言與其他高級語言一樣,都有反射功能斩狱。
Go 反射包
reflect包有兩個數(shù)據(jù)類型是最重要的耳高,一個是Type,一個是Value所踊。
Type就是定義的類型的一個數(shù)據(jù)類型泌枪,Value是值的類型。具體的Type和Value里面包含的方法參看文檔:https://pkg.go.dev/reflect?tab=doc
簡單示例
說明秕岛,本示例介紹如何通過反射訪問包碌燕,包的字段屬性類型,字段屬性值继薛,以及如何修改屬性值修壕。 本示例沒有介紹如何訪問方法以及動態(tài)調(diào)用方法。
package main
import (
"fmt"
"reflect"
)
type DeviceStatus uint8
const (
Offline DeviceStatus = 0
Online DeviceStatus = 1
)
type Category struct {
ID int32
Name string `json:"name" value:"空調(diào)"`
Description string
}
func main() {
var category Category
var i int32 = -5
// 類型(Type)指的是系統(tǒng)原生數(shù)據(jù)類型遏考,如 int慈鸠、string、bool诈皿、float32 等類型林束,以及使用 type 關(guān)鍵字定義的類型
// 種類(Kind)指的是對象歸屬的品種. 在go語言中是固定定義好的,可以通過查看Kind定義知道全部Kind
typeInfo, kindInfo := reflectTypeAndKind(category)
fmt.Printf("struct type reflect info. name:%s, kind:%s \n", typeInfo, kindInfo)
enumerateFieldByReflect(category)
typeOfCagegory := reflect.TypeOf(category)
typeInfo, kindInfo = reflectTypeAndKind(typeOfCagegory)
fmt.Printf("type reflect info of reflect. name:%s, kind:%s \n", typeInfo, kindInfo)
enumerateFieldByReflect(category)
fmt.Println("categroy is not initialized.")
getAndUpdateFieldValueByReflect(&category)
category = Category{ID:001, Name: "空調(diào)", Description: "空調(diào)大類"}
fmt.Printf("---updateFieldValue by reflect. rawValue:%v \n\n", category)
fmt.Println("categroy is initialized.")
fmt.Printf("---enumerateFieldValue by reflect. rawValue:%v \n", category)
enumerateFieldByReflect(category)
fmt.Printf("---start of updateFieldValue by reflect. rawValue:%v \n", category)
getAndUpdateFieldValueByReflect(&category)
fmt.Printf("---end of updateFieldValue by reflace. newValue:%v \n\n", category)
typeInfo, kindInfo = reflectTypeAndKind(i)
fmt.Printf("primitive type reflect info. name:%s, kind:%v \n", typeInfo, kindInfo)
enumerateFieldByReflect(i)
getAndUpdateFieldValueByReflect(i)
myFunc := reflectTypeAndKind
typeInfo, kindInfo = reflectTypeAndKind(myFunc)
fmt.Printf("func type reflect info. name:%s, kind:%v \n", typeInfo, kindInfo)
enumerateFieldByReflect(myFunc)
getAndUpdateFieldValueByReflect(myFunc)
var devStatus DeviceStatus = Online
typeInfo, kindInfo = reflectTypeAndKind(devStatus)
fmt.Printf("enum type reflect info. name:%s, kind:%v \n", typeInfo, kindInfo)
enumerateFieldByReflect(devStatus)
getAndUpdateFieldValueByReflect(devStatus)
}
func reflectTypeAndKind(x interface{}) (typeInfo string, kindInfo reflect.Kind) {
reflectObject := reflect.TypeOf(x)
return reflectObject.Name(), reflectObject.Kind()
}
func enumerateFieldByReflect(x interface{}) {
reflectObject := reflect.TypeOf(x)
reflectValue := reflect.ValueOf(x)
// NumField returns a struct type's field count.
// It panics if the type's Kind is not Struct.
if reflectObject.Kind() == reflect.Struct {
num := reflectObject.NumField();
fmt.Printf("there are %d fields\n", num)
for i := 0; i < num; i++ {
// 獲取每個屬性的結(jié)構(gòu)體字段類型
fieldType := reflectObject.Field(i)
filedValue := reflectValue.Field(i)
fieldKind := filedValue.Kind()
var rawIntValue int32
var rawStrValue string
switch fieldKind {
case reflect.Int32:
//獲取64位的值稽亏,強(qiáng)制類型轉(zhuǎn)換為int類型
rawIntValue = filedValue.Interface().(int32)
case reflect.String:
rawStrValue = filedValue.Interface().(string)
default:
}
// 輸出屬性名和tag
fmt.Printf("%dth, name: %v, type %v, tag: '%v', currentIntValue:%v, currentStrValue:%v \n",
i, fieldType.Name, fieldType.Type, fieldType.Tag, rawIntValue, rawStrValue)
}
// 通過字段名, 找到字段類型信息
if nameField, ok := reflectObject.FieldByName("Name"); ok {
// 從tag中取出需要的tag
fmt.Println(nameField.Tag.Get("json"), nameField.Tag.Get("value"))
} else {
fmt.Println("no name filed")
}
// It panics if v's Kind is not struct.
fmt.Println("不存在的結(jié)構(gòu)體成員:", reflect.ValueOf(x).FieldByName("").IsValid())
} else {
fmt.Println("non-struct, no filed")
}
}
/*
* 更新值壶冒,必須傳入指針類型, 反射只能修改可以導(dǎo)出的屬性(也就是大寫字母開始的屬性)
*/
func getAndUpdateFieldValueByReflect(x interface{}) {
reflectObject := reflect.TypeOf(x)
reflectValue := reflect.ValueOf(x)
reflectKind := reflectObject.Kind()
actualReflectKind := reflect.Ptr
if reflectKind == reflect.Ptr {
actualReflectKind = reflect.Struct
fmt.Printf("ptr type: %T\n", x)
reflectObject = reflectObject.Elem()
actualReflectKind = reflectObject.Kind()
reflectValue = reflectValue.Elem()
}
// NumField returns a struct type's field count.
// It panics if the type's Kind is not Struct.
if actualReflectKind == reflect.Struct {
num := reflectObject.NumField();
fmt.Printf("there are %d fields, reflectKind:%v, actualReflectKind:%v\n",
num, reflectKind, actualReflectKind)
for i := 0; i < num; i++ {
// 獲取每個屬性的結(jié)構(gòu)體字段類型
fieldType := reflectObject.Field(i)
filedValue := reflectValue.Field(i)
fieldKind := filedValue.Kind()
// 輸出屬性名和tag
fmt.Printf("%dth, name: %v, type %v, tag: '%v', filedValue:%v, fieldValueInterface:%v \n",
i, fieldType.Name, fieldType.Type, fieldType.Tag, filedValue, filedValue.Interface())
switch fieldKind {
case reflect.Int32:
newIntValue := 999 + filedValue.Interface().(int32)
// 強(qiáng)制將int32轉(zhuǎn)換為int64截歉,否則無法傳入?yún)?shù)
filedValue.SetInt(int64(newIntValue))
case reflect.String:
newStrValue := "aaa-" + filedValue.Interface().(string)
filedValue.SetString(newStrValue)
default:
}
}
// 通過字段名, 找到字段類型信息
if nameField, ok := reflectObject.FieldByName("Name"); ok {
fmt.Println(nameField.Tag.Get("json"), nameField.Tag.Get("value"), reflectValue.FieldByName("Name"))
} else {
fmt.Println("no name filed")
}
} else {
fmt.Printf("non-struct, no filed. reflectKind:%v, rawValue: %v \n", reflectKind, reflectValue)
}
}
運行結(jié)果:
```bash
C:\F\yqgopath\src\github.com\mygototurials\reflectdemo>go run main.go
struct type reflect info. name:Category, kind:struct
there are 3 fields
0th, name: ID, type int32, tag: '', currentIntValue:0, currentStrValue:
1th, name: Name, type string, tag: 'json:"name" value:"空調(diào)"', currentIntValue:0, currentStrValue:
2th, name: Description, type string, tag: '', currentIntValue:0, currentStrValue:
name 空調(diào)
不存在的結(jié)構(gòu)體成員: false
type reflect info of reflect. name:, kind:ptr
there are 3 fields
0th, name: ID, type int32, tag: '', currentIntValue:0, currentStrValue:
1th, name: Name, type string, tag: 'json:"name" value:"空調(diào)"', currentIntValue:0, currentStrValue:
2th, name: Description, type string, tag: '', currentIntValue:0, currentStrValue:
name 空調(diào)
不存在的結(jié)構(gòu)體成員: false
categroy is not initialized.
ptr type: *main.Category
there are 3 fields, reflectKind:ptr, actualReflectKind:struct
0th, name: ID, type int32, tag: '', filedValue:0, fieldValueInterface:0
1th, name: Name, type string, tag: 'json:"name" value:"空調(diào)"', filedValue:, fieldValueInterface:
2th, name: Description, type string, tag: '', filedValue:, fieldValueInterface:
name 空調(diào) aaa-
---updateFieldValue by reflect. rawValue:{1 空調(diào) 空調(diào)大類}
categroy is initialized.
---enumerateFieldValue by reflect. rawValue:{1 空調(diào) 空調(diào)大類}
there are 3 fields
0th, name: ID, type int32, tag: '', currentIntValue:1, currentStrValue:
1th, name: Name, type string, tag: 'json:"name" value:"空調(diào)"', currentIntValue:0, currentStrValue:空調(diào)
2th, name: Description, type string, tag: '', currentIntValue:0, currentStrValue:空調(diào)大類
name 空調(diào)
不存在的結(jié)構(gòu)體成員: false
---start of updateFieldValue by reflect. rawValue:{1 空調(diào) 空調(diào)大類}
ptr type: *main.Category
there are 3 fields, reflectKind:ptr, actualReflectKind:struct
0th, name: ID, type int32, tag: '', filedValue:1, fieldValueInterface:1
1th, name: Name, type string, tag: 'json:"name" value:"空調(diào)"', filedValue:空調(diào), fieldValueInterface:空調(diào)
2th, name: Description, type string, tag: '', filedValue:空調(diào)大類, fieldValueInterface:空調(diào)大類
name 空調(diào) aaa-空調(diào)
---end of updateFieldValue by reflace. newValue:{1000 aaa-空調(diào) aaa-空調(diào)大類}
primitive type reflect info. name:int32, kind:int32
non-struct, no filed
non-struct, no filed. reflectKind:int32, rawValue: -5
func type reflect info. name:, kind:func
non-struct, no filed
non-struct, no filed. reflectKind:func, rawValue: 0x49e950
enum type reflect info. name:DeviceStatus, kind:uint8
non-struct, no filed
non-struct, no filed. reflectKind:uint8, rawValue: 1
C:\F\yqgopath\src\github.com\mygototurials\reflectdemo>
對代碼的解釋
1胖腾, 使用 reflect.TypeOf() 函數(shù)可以獲得任意類型的類型對象(reflect.Type),程序通過類型對象可以訪問任意類型的類型信息瘪松。下面通過例子來理解獲取類型對象的過程:
TypeOf方法額返回值為Type
// TypeOf returns the reflection Type that represents the dynamic type of i.
// If i is a nil interface value, TypeOf returns nil.
func TypeOf(i interface{}) Type {
eface := *(*emptyInterface)(unsafe.Pointer(&i))
return toType(eface.typ)
}
type.Kind() 直接返回具體的int或者string之類的咸作, 我們可以看Kind的定義:
// A Kind represents the specific kind of type that a Type represents.
// The zero Kind is not a valid kind.
type Kind uint
const (
Invalid Kind = iota
Bool
Int
Int8
Int16
Int32
Int64
Uint
Uint8
Uint16
Uint32
Uint64
Uintptr
Float32
Float64
Complex64
Complex128
Array
Chan
Func
Interface
Map
Ptr
Slice
String
Struct
UnsafePointer
)
2, 使用 reflect.ValueOf() 函數(shù)可以獲得任意值的類型對象(reflect.Value)宵睦,程序通過值類型對象可以訪問任意值的類型信息和值當(dāng)前內(nèi)容记罚。下面通過例子來理解獲取類型對象的過程:
type方法額返回值為Type
// ValueOf returns a new Value initialized to the concrete value
// stored in the interface i. ValueOf(nil) returns the zero Value.
func ValueOf(i interface{}) Value {
if i == nil {
return Value{}
}
// TODO: Maybe allow contents of a Value to live on the stack.
// For now we make the contents always escape to the heap. It
// makes life easier in a few places (see chanrecv/mapassign
// comment below).
escapes(i)
return unpackEface(i)
}
3, 通過反射獲取指針指向的元素類型:reflect.Elem()壳嚎。 例如我們傳遞44行桐智, getAndUpdateFieldValueByReflect(&category)
那么就可以通過reflectObject = reflectObject.Elem()得到真實的元素類型
reflectObject := reflect.TypeOf(x)
reflectValue := reflect.ValueOf(x)
reflectKind := reflectObject.Kind()
actualReflectKind := reflect.Ptr
if reflectKind == reflect.Ptr {
actualReflectKind = reflect.Struct
fmt.Printf("ptr type: %T\n", x)
reflectObject = reflectObject.Elem()
actualReflectKind = reflectObject.Kind()
reflectValue = reflectValue.Elem()
}