How to create an object with Reflection

polaris · · 627 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m trying to figure out how to replace an explicit creation of a typed object with a type that&#39;s contained in an interface at runtime.</p> <p>if I create it EXPLICITLY it works. If I IMPLICITLY create the object it panics.</p> <p>Here&#39;s the code below:</p> <pre><code>package main import ( &#34;fmt&#34; &#34;reflect&#34; ) func main() { myData := make(map[string]interface{}) myData[&#34;name&#34;] = &#34;bob&#34; myData[&#34;age&#34;] = 25 result := &amp;MyStruct{} FillStruct(myData, result) fmt.Printf(&#34;%s is %d\n&#34;, result.Name, result.Age) } func FillStruct(data map[string]interface{}, result interface{}) { t := reflect.ValueOf(result).Elem() typ := t.Type() fmt.Printf(&#34;interface is of type [%s]\n&#34;, typ.Name()) // EXPLICIT creation of struct --works ms := MyStruct{} // IMPLICIT creation of struct -- fails ms:=reflect.New(reflect.ValueOf(result).Type()).Elem() fmt.Printf(&#34;created a [%T]\n&#34;, reflect.ValueOf(ms).Type()) st := reflect.TypeOf(ms) fmt.Printf(&#34;%d fields\n&#34;, st.NumField()) fmt.Printf(&#34;[%s] [%s]\n&#34;, st.Name(), reflect.TypeOf(ms).Name()) for i := 0; i &lt; st.NumField(); i++ { field := st.Field(i) json := field.Tag.Get(&#34;json&#34;) name := field.Name fmt.Printf(&#34;json [%s] field [%s]\n&#34;, json, name) val := t.FieldByName(field.Name) val.Set(reflect.ValueOf(data[json])) } } type MyStruct struct { Name string `json:&#34;name&#34; binding:required` Age int `json:&#34;age&#34;` } </code></pre> <hr/>**评论:**<br/><br/>pierrrre: <pre><p>With fmt.Printf(&#34;type of ms: %T\n&#34;, ms) you can check the type of ms.</p> <p>ms := MyStruct{}</p> <p>type of ms: main.MyStruct</p> <p>ms := reflect.New(reflect.ValueOf(result).Type()).Elem()</p> <p>type of ms: reflect.Value</p></pre>Rabarar: <pre><p>Not sure I see your point. You can see that I&#39;ve printed out the type of each object in the code...</p> <p>The question is how to create an equivalent type to an explicit declaration. </p></pre>Rabarar: <pre><p>SOLVED!</p> <p>It turns out that the magic sauce to create an instance at runtime looks like this:</p> <pre><code>t := reflect.ValueOf(result).Elem() typ := t.Type() ms:=(reflect.New(typ).Elem()).Interface() </code></pre></pre>Logiraptorr: <pre><p>Just to clarify, It&#39;s more direct to use TypeOf instead of ValueOf.</p> <pre><code>t := reflect.TypeOf(result).Elem() ms := reflect.New(t).Elem().Interface() </code></pre></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

627 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传