golang-reflect

2018-04-26  本文已影响24人  6a91e15c5cde

reflect 示例0

package main

func main(){
    x := 123
    v := reflect.ValueOf(&x)
    v.Elem().SetInt(999)

    fmt.Println(x)
}

reflect示例1

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Id int
    Name string
    Age int
}


func (u User) Hello(){
    fmt.Println("Hello world")
}

func Info(o interface{}){
    t := reflect.TypeOf(o)
    fmt.Println("Type: ",t.Name())


    v :=reflect.ValueOf(o)
    fmt.Println("Filds: ")

    for i :=0;i<t.NumField();i++ {
        f :=t.Field(i)
        val := v.Field(i).Interface()
        fmt.Printf("%6s: %v = %v\n",f.Name,f.Type,val)
    }

    for i :=0;i< t.NumMethod();i++ {
        m := t.Method(i)
        fmt.Printf("%6s: %v\n",m.Name,m.Type)
    }
}


func main(){
    u := User{1,"tom",20}
    Info(u)
}

reflect 示例2

通过反射修改对象属性


package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Id int
    Name string
    Age int
}

func Set(o interface{}) {
    v := reflect.ValueOf(o)

    if v.Kind() == reflect.Ptr && !v.Elem().CanSet() {
        fmt.Println("xxx")
        return
    } else {
        v = v.Elem()
    }

    f := v.FieldByName("Name")
    if !f.IsValid() {
        fmt.Println("BAD")
        return
    }

    if f.Kind() == reflect.String {
        f.SetString("BYEBYE")
    }
}


func main(){
    u := User{1,"hans",123}
    Set(&u)
    fmt.Println(u)
}

reflect 示例3

通过反射调用方法

package main

import (
    "fmt"
    "reflect"
)

type User struct {
    Id int
    Name string
    Age int
}


func (u User) Hello(name string){
    fmt.Println("Name:",name,",My name is ",u.Name)
}

func main(){
    u := User{1,"hans",123}
    //u.Hello("DCR")

    v := reflect.ValueOf(u)
    mv := v.MethodByName("Hello")

    args :=[]reflect.Value{reflect.ValueOf("joe")}
    mv.Call(args)
}
上一篇下一篇

猜你喜欢

热点阅读