golang反射用法举例(注册插件)

有关golang反射的内容,网上有大量讲述,请自行google——"golang反射三法则"

下面主要反射在实际中的一种应用,插件注册与插件管理

package main

import (
    "fmt"

    "reflect"
)

type MyInterface interface {
    Test()
}

type Mytype1 struct {
    A string
    B string
}

func (m Mytype1) Test() {
    fmt.Println("test type1", m)
}

type Mytype2 struct {
    A string
    B string
}

func (m Mytype2) Test() {
    fmt.Println("test type2", m)
}

func main() {
    // testType1 testType2模拟两个注册的插件,实际可在各.go的init()方式实现
    testType1 := reflect.TypeOf((*Mytype1)(nil)).Elem()
    testType2 := reflect.TypeOf((*Mytype2)(nil)).Elem()

    types := []reflect.Type{testType1, testType2}
    fmt.Println("types:", types)

    // 模拟插件管理,统一调用
    var instance interface{}
    for _, testType := range types {
        instance = reflect.New(testType).Interface()
        if myinterface, ok := instance.(MyInterface); ok {
            //模拟统一调用
            myinterface.Test()
        }

    }

}

输出:

types: [main.Mytype1 main.Mytype2]
test type1 { }
test type2 { }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,870评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,841评论 18 139
  • 在我们生活的这个星球上,无论什么年龄,什么肤色的人们,无不希望自己生活得快乐喜悦,平安健康,过上金钱富足的幸福人生...
    兰姐美式减脂倡导者阅读 1,067评论 0 4
  • (七)谈到哪儿啦?原谅我有些健忘。事实上,生活中我常常健忘。上学期,我一个月内丢掉了四五个优盘。没法,在同一家店买...
    皮卡丘的orchid阅读 166评论 0 0
  • 暑假里奶奶和爸爸带着我去上海玩了四天,我们去过苏州的周庄,上海的迪士尼乐园、田子坊、上海外滩,还有城隍庙...
    徐雨恒阅读 248评论 1 2