프로그래밍 검색 블로그

go reflect 호출 본문

go

go reflect 호출

코딩조무사 2018. 5. 15. 22:15
package main

import (
	"fmt"
	"reflect"
)

type controller struct {
}

func (c controller) Foo(a int, b string) string {
	fmt.Println("Foo")
	return fmt.Sprint(a, b)
}
func (c controller) Koo(a int, b string) string {
	fmt.Println("Koo")
	return fmt.Sprint(a, b)
}

func (c controller) goo() {
	//private는 안보임
}

//reflection으로 함수 호출할때는 일반 인자 대신 reflect.Value를 넣는다
func valueToReflectionArguments(args ...interface{}) []reflect.Value {
	length := len(args)
	reflectArgs := make([]reflect.Value, 0, length)
	for i := 0; i < length; i++ {
		reflectArgs = append(reflectArgs, reflect.ValueOf(args[i]))
	}
	return reflectArgs
}

func main() {

	c := controller{}

	//포인터를 넘기고 싶다면 reflect.TypeOf(&c)
	myType := reflect.TypeOf(c)

	//메서드 모두 호출
	//혹은 myType.MethodByName으로 이름으로 검색
	//Public멤버만 검색하고 한글 시작은 private이 됨
	for i := 0; i < myType.NumMethod(); i++ {
		method := myType.Method(i)
		ret := method.Func.Call(valueToReflectionArguments(c, 3, "test"))
		fmt.Println(ret[0].String())
	}
}


'go' 카테고리의 다른 글

go context Timeout, deadline  (0) 2018.12.22
go AES 암호화  (0) 2018.05.22
go 파일 압축  (0) 2018.05.12
Comments