zoukankan      html  css  js  c++  java
  • go通过名称来调用对应的方法

    仅仅是为了学习go语言中的反射。

    package main
    
    import (
    	"errors"
    	"fmt"
    	"reflect"
    )
    
    func Call(m map[string]interface{}, name string, params ...interface{}) ([]reflect.Value,error) {
    	_, found := m[name]
    	if !found {
    		return nil, errors.New("map do not contains key ...")
    	}
    	fv := reflect.ValueOf(m[name])
    	if fv.Kind() != reflect.Func {
    		return nil, errors.New("the value of key is not a function")
    	}
    
    	if len(params) != fv.Type().NumIn() {
    		return nil, errors.New("argument passed in does not match the function")
    	}
    
    	in := make([]reflect.Value, len(params))
    	// for i := 0; i < len(params); i++ {
    	// 	in[i] = reflect.ValueOf(params[i])
    	// }
    	for i, param := range params {
    		in[i] = reflect.ValueOf(param)
    	}
    	return fv.Call(in), nil
    }
    
    func test1(name string) {
    	fmt.Printf("hello,%s 
    ", name)
    }
    
    func test2(name string, age int) {
    	fmt.Printf("hello,my name is %s ,%d years old", name, age)
    }
    
    func main() {
    	m := make(map[string]interface{})
    	m["test1"] = test1
    	m["test2"] = test2
    
    	result, err := Call(m, "test2", "hupeng", 12)
    	if err != nil {
    		panic(err)
    	}
    	fmt.Println(result)
    
    }
    
    
  • 相关阅读:
    234. Palindrome Linked List
    Remove duplicates
    Unsorted, maximum ==> sorted
    Find one unique integer
    TwoSum
    13. Roman to Integer
    38. Count and Say
    543. Diameter of Binary Tree
    LuoguP1131 [ZJOI2007]时态同步 (树形DP,贪心)
    Luogu3177 [HAOI2015]树上染色 (树形DP)
  • 原文地址:https://www.cnblogs.com/hupengcool/p/4128522.html
Copyright © 2011-2022 走看看