5...
//new object same the type as sample
func New(sample interface{}) interface{} {
t :=reflect.ValueOf(sample).Type()
v :=reflect.New(t).Interface()
returnv
}
func CheckType(val interface{}, kind reflect.Kind) bool {
v :=reflect.ValueOf(val)
return kind== v.Kind()
}
func Call(_func interface{}, params ...interface{}) (result[]interface{}, err error) {
f :=reflect.ValueOf(_func)
iflen(params) != f.Type().NumIn() {
ss := fmt.Sprintf("The number of params is not adapted.%s",f.String())
panic(ss)
return
}
var in[]reflect.Value
iflen(params) > 0 { //prepare in paras
in = make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
}
out :=f.Call(in)
if len(out)> 0 { //prepare out paras
result = make([]interface{}, len(out), len(out))
for i, v := range out {
result[i] = v.Interface()
}
}
return
}
func ChanRecv(ch interface{}) (r interface{}) {
v :=reflect.ValueOf(ch)
if x, ok :=v.Recv(); ok {
r = x.Interface()
}
return
}
func reflect_struct_info(it interface{}) {
t :=reflect.TypeOf(it)
fmt.Printf("interface info:%s %s %s %s\n", t.Kind(), t.PkgPath(),t.Name(), t)
if t.Kind()== reflect.Ptr { //if it is pointer, get it element type
tt := t.Elem()
if t.Kind() == reflect.Interface {
fmt.Println(t.PkgPath(), t.Name())
for i := 0; i < tt.NumMethod(); i++ {
f := tt.Method(i)
fmt.Println(i, f)
}
}
}
v :=reflect.ValueOf(it)
k :=t.Kind()
if k ==reflect.Ptr {
v = v.Elem() //指針轉換爲對應的結構
t = v.Type()
k = t.Kind()
}
fmt.Printf("value type info:%s %s %s\n", t.Kind(), t.PkgPath(),t.Name())
if k ==reflect.Struct { //反射結構體成員信息
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
fmt.Printf("%s %v\n", i, f)
}
for i := 0; i < t.NumMethod(); i++ {
f := t.Method(i)
fmt.Println(i, f)
}
fmt.Printf("Fileds:\n")
f := v.MethodByName("func_name")
if f.IsValid() { //執行某個成員函數
arg := []reflect.Value{reflect.ValueOf(int(2))}
f.Call(arg)