go語言中的反射Reflect初探

我們先看看什么是反射,它有什么用。
我們先看卡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()

    } 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末末早,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子说庭,更是在濱河造成了極大的恐慌然磷,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,273評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件刊驴,死亡現(xiàn)場離奇詭異姿搜,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)捆憎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評論 3 398
  • 文/潘曉璐 我一進(jìn)店門舅柜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人攻礼,你說我怎么就攤上這事业踢。” “怎么了礁扮?”我有些...
    開封第一講書人閱讀 167,709評論 0 360
  • 文/不壞的土叔 我叫張陵知举,是天一觀的道長。 經(jīng)常有香客問我太伊,道長雇锡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,520評論 1 296
  • 正文 為了忘掉前任僚焦,我火速辦了婚禮锰提,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘芳悲。我一直安慰自己立肘,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,515評論 6 397
  • 文/花漫 我一把揭開白布名扛。 她就那樣靜靜地躺著谅年,像睡著了一般。 火紅的嫁衣襯著肌膚如雪肮韧。 梳的紋絲不亂的頭發(fā)上融蹂,一...
    開封第一講書人閱讀 52,158評論 1 308
  • 那天,我揣著相機(jī)與錄音弄企,去河邊找鬼超燃。 笑死,一個胖子當(dāng)著我的面吹牛拘领,可吹牛的內(nèi)容都是我干的意乓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,755評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼约素,長吁一口氣:“原來是場噩夢啊……” “哼届良!你這毒婦竟也來了本涕?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,660評論 0 276
  • 序言:老撾萬榮一對情侶失蹤伙窃,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后样漆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體为障,經(jīng)...
    沈念sama閱讀 46,203評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,287評論 3 340
  • 正文 我和宋清朗相戀三年放祟,在試婚紗的時候發(fā)現(xiàn)自己被綠了鳍怨。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,427評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡跪妥,死狀恐怖鞋喇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情眉撵,我是刑警寧澤侦香,帶...
    沈念sama閱讀 36,122評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站纽疟,受9級特大地震影響罐韩,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜污朽,卻給世界環(huán)境...
    茶點故事閱讀 41,801評論 3 333
  • 文/蒙蒙 一散吵、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蟆肆,春花似錦矾睦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至亡问,卻和暖如春官紫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背州藕。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工束世, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人床玻。 一個月前我還...
    沈念sama閱讀 48,808評論 3 376
  • 正文 我出身青樓毁涉,卻偏偏與公主長得像,于是被迫代替她去往敵國和親锈死。 傳聞我的和親對象是個殘疾皇子贫堰,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,440評論 2 359